Project Euler #6: Sum square difference | Hackerrank | Project Euler

 

 Sum square difference 


The sum of the squares of the first ten natural numbers is, 1^2+2^2+...+10^2=385 . The square of the sum of the first ten natural numbers is, (1+2+...+10)^2 = 55^2 = 3025 . Hence the absolute difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025-385=2640.

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

Input Format

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

Constraints

1<=T<=10^4

1<=N<=10^4

Output Format

Print the required answer for each test case.

Sample Input 0

2

3

10

Sample Output 0

22

2640


Explanation 0

For N=3 , (1+2+3)^2 - (1^2+2+^2+3^2) = 22

For N=10 , (1+2+...+10)^2 - (1^2+2^2+...10^2) = 2640 

Solution 

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int t; 
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0++){
        long long n; 
        scanf("%lld",&n);
        long long f1,f2,diff;
        f1=(n*(n+1))/2;
        f1=f1*f1;
        f2=(n*(n+1)*(2*n+1))/ 6;
        diff=(f1-f2);
        if (diff<0)
        diff=diff*-1;
        printf("%lld\n",diff);
    }
    return 0;
}


You can also run it on an online IDE:

https://ide.geeksforgeeks.org/6601fb42-0c0f-4c75-8058-27c871f50f58

Your feedback are always welcome! If you have any doubt you can contact me or leave a comment!  Happy Coding !! Cheers!!!


No comments:

Post a Comment

Super Market Problem | TCS Code Vita 2023 - Zone 1 | Super Market TCS Code Vita 2023 Solution | Code Vita 2023 | Code Vita 2023 season 11 solution

 Problem Description: In a Super market we will find many variations of the same product. In the same way we can find many types of rice bag...