Calculate Difference Between Square Sum First N Number in python


Write a Python program to calculate the difference between the squared sum of first n natural numbers and the sum of squared first n natural numbers.(default value of number=2).


This program calculates the difference between the sum of the squares of the first n natural numbers and the square of the sum of the first n natural numbers. Firstly, the program initializes the value of n as 23. Then, it declares two variables sum_of_squares and square_of_sum to store the sum of the squares and square of sum of the numbers respectively.

Then, a for loop is used to iterate over the range of numbers from 1 to n+1. Inside the loop, it calculates the sum of the squares of the numbers by multiplying each number with itself and adding it to the sum_of_squares variable. It also calculates the sum of the numbers by adding each number to the square_of_sum variable.

After the loop, it calculates the square of the sum by squaring the square_of_sum variable. Finally, it prints the difference between the square_of_sum and sum_of_squares which is the required result.

Source Code

n=23
sum_of_squares = 0
square_of_sum = 0
for num in range(1, n+1):
    sum_of_squares += num * num
    square_of_sum += num
 
square_of_sum = square_of_sum ** 2
 
print(square_of_sum - sum_of_squares)

Output

71852

Example Programs