Example HTML page

Sum of Square Series

In this post I will show you how to write a Python program to calculate sum of series 1²+2²+3²+….+n².

The following is the mathematical formula for Sum of series:

1²+2²+3²+….+n² = ( n (n+1) (2n+1)) / 6.

#Program to calculate sum of series 1²+2²+3²+….+n² by using the above formula.

num = int(input("Enter any Positive Number  : "))

sum = 0

sum = (num * (num + 1) * (2 * num + 1)) / 6

print("The Sum of Series upto {0}  = {1}".format(num, sum))

Output

Enter any Positive Number  : 7

The Sum of Series upto 7  = 140.0

Calculation

num=7

sum = (num * (num + 1) * (2 * num + 1)) / 6

sum=(7 * (7 + 1) * (2 * 7 +1)) / 6

sum=140.0

# Program to calculate Sum of Series 1²+2²+3²+….+n² for loop.

num = int(input("Enter any Positive Number  : "))
sum = 0
sum = (num * (num + 1) * (2 * num + 1)) / 6
for i in range(1, num + 1):
    if(i != num):
        print("%d^2 + " %i, end = ' ')
    else:
        print("{0}^2 = {1}".format(i, sum))

Output

Enter any Positive Number  : 7

1^2 +  2^2 +  3^2 +  4^2 +  5^2 +  6^2 +  7^2 = 140.0

#Python Program to calculate Sum of Series 1²+2²+3²+….+n² using functions

def sum_of_square_series(num):
   sum=0
   sum = (num * (num + 1) * (2 * num + 1)) / 6
   for i in range(1, num + 1):
    if(i != num):
        print("%d^2 + " %i, end = ' ')
    else:
        print("{0}^2 = {1}".format(i, sum))
N= int(input("Enter any Positive Number  : "))
sum_of_square_series(N)

Output

Enter any Positive Number  : 7

1^2 +  2^2 +  3^2 +  4^2 +  5^2 +  6^2 +  7^2 = 140.0

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest