## Sum square difference

### Problem 6

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 3025

Hence the 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 difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Ans:-

code:-

def sqrsum(n):
sum=0
for i in range(0,n+1):
sum=sum+(i*i)
return sum
def sumsqr(n):
sum=0
for i in range(0,n+1):
sum=sum+i
return(sum*sum)
n=100
print(sumsqr(n)-sqrsum(n))

Programming problem form Hackerrank.com

The sum of the squares of the first ten natural numbers is,12+22+…+102 =385. The square of the sum of the first ten natural numbers is,(1+2+…+10)2 =552=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  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⩽ 104
• 1⩽N⩽ 104

Output Format

Print the required answer for each test case.

Sample Input

2
3
10

Sample Output

22
2640

Explanation

• For N=3 ,(1+2+3)2-(12+22+32) ⇒22
• For ,N=10,(1+2+…+10)2-(12+22+…+102) ⇒2640

Solution:-

•  Computers are fast, so we can implement this solution directly without any clever math.
•  However for the mathematically inclined, there are closed-form formulas:
s = N(N + 1) / 2.
s2 = N(N + 1)(2N + 1) / 6.
Hence s^2 – s2 = (N^4 / 4) + (N^3 / 6) – (N^2 / 4) – (N / 6).

Code:-

def sqrsum(n):
sum=0
for i in range(0,n+1):
sum=sum+(i*i)
return sum
def sumsqr(n):
sum=0
for i in range(0,n+1):
sum=sum+i
return(sum*sum)

t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(sumsqr(n)-sqrsum(n))