Optimising the code

The question is this: https://www.hackerrank.com/challenges/summing-the-n-series

I've written the following code. The code is correct, but fails in some test cases on hackerrank when a big input is given.
So, what I want to know is how to make this code run faster.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include<cmath>
using namespace std;
int main(int argc, char *argv[])
{
	int div;
	div=(1e+9)+7;
	int T,n;
	int sum=0;
	cin>>T;
	if(T>10)
	{
		return 1;;
	}
	for(int i=1;i<=T;i++)
	{
		sum=0;
		cin>>n;
		if(n>(1e+16))
		{
			return 2;
		}
		
		for(int j=1;j<=n;j++)
		{
			sum=sum+(j*j-(j-1)*(j-1));
		}
		sum=sum%div;
		cout<<sum<<endl;
	}
	return 0;
}
Try to optimise your sequence:
Sn = Tn + Tn-1 + Tn-2 + ... + T2 + T1
T(n) = n2 - (n - 1)2
Substitute Ta into Sn:
Sn = n2 - (n - 1)2 + (n - 1)2 - (n - 2)2 + (n - 2)2 - (n - 3)2 + ... + 22 - 12 + 12 - 02
Do you see how this series can be simplified now?
Last edited on
Topic archived. No new replies allowed.