Time spent here:

Thursday, 2 June 2016

Project Euler #6: Sum square difference

The sum of the squares of the first ten natural numbers is, . The square of the sum of the first ten natural numbers is, . Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is .
eg:consider n as 10.
1^2+2^2+3^2+......+10^2=385
(1+2+3+4+...+10)^2=3025
sum difference = 3025-385=2640

Find the difference between the sum of the squares of the first  natural numbers and the square of the sum.

Input Format 
First line contains  that denotes the number of test cases. This is followed by  lines, each containing an integer, .

Output Format 
Print the required answer for each test case.

Constraints 

Sample Input

2
3
10
Sample Output

22
2640

c implementation:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

   long long int i,j,n,t;
    scanf("%lld",&t);
    while(t--)
    {
      scanf("%lld",&n);
      long long int sq=((n*(n+1))*((2*n)+1))/6;
      long long int sum=((n*(n+1)))/2;
      printf("%lld\n",sum*sum-sq);  
    }
    return 0;
}

No comments:

Post a Comment