PCJ18B - Editorial

This is called as explanation brother :grinning:

1 Like

Try to run your program for n=5. Your program is giving incorrect answer i.e., 34. Correct answer is 35.

type or paste code here#include <iostream>
using namespace std;

int main() {
    //o(1)
   int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		int ans=0;
		if(n%2!=0){
			int i=(n+1)/2;
			ans=((2*i+1)*(i)*(2*i-1))/3;
		}
		else{
			int i=n/2;
			ans=(2*((2*i+1)*(i)*(i+1)))/3;
		}
		cout<<ans<<endl;
	}

}

A nice and simple solution which is O(1) as well is n^2 + n choose 3 which can be simplified to the following expression:

#include <bits/stdc++.h>
using namespace std;

int main() {
int t;
cin >> t;
while(t–) {
int n;
cin >> n;
cout << (n**n) + ((n*(n-1)*(n-2))/6) << ‘\n’;
}
return 0;
}
Note I put two * since the website removes the multiplication but it just means n^2.