python program for sum of squares of first n natural numbers

In this article let's look at how to find  the sum of square of the first n natural number.

Sum of squares of first n natural numbers is denoted As given below.

12 + 22 + 32 + 42 + ………… + n2


Where n is a number



For example:

let's take n value as 50 it will be denoted as

12 + 22 + 32 + 42 + 52 = 1 + 4 + 9 + 16 + 25 = 55


There is another way to find the sum of squares of a number using a formula.  the sum of squares of n natural number is denoted as given below

Σn2 = [n(n+1)(2n+1)]/6


Where n is a natural number



Let's assume n as 5

Then the above formula evaluates to

(5 * (5+1) * (2*5 + 1)) / 6 = (5 * 6 * 11) / 6 = 55

So from the above theory there are two ways to solve the  program in Python

1) Using  iterative method using a for loop
2) Using the formula


python program for sum of squares of first n natural numbers




Python program for sum of squares of first n natural numbers

Let's take a variable number and ask the user to enter the number,  convert it into an integer.  then take another variable total and initialize it to zero.

Now take a for loop and start traversing from 1 up to number + 1. Add the total to the index item rise to power of 2 using double star operator. Finally print the total. 

 
number = int(input("Enter a Number : "))

total = 0
for index in range(1, number + 1):
   total += index ** 2

print("Sum of Squares of n Natural Number is : ", total)


OUTPUT :
Enter a Number : 25
Sum of Squares of n Natural Number is :  5525

 

 

python program for sum of squares of first n natural numbers using Formula.

Let's take a variable number and ask the user to enter the number,  convert it into an integer.  

Take another variable total and Try to use the below formula to find the sum of squares of n natural numbers. after completion print  the total.

Σn2 = [n(n+1)(2n+1)]/6



number = int(input("Enter a Number : "))
total = (number * (number + 1) * (number * 2 + 1)) / 6
print("Sum of Squares of n Natural Number is : ", total)



OUTPUT :
Enter a Number : 25
Sum of Squares of n Natural Number is :  5525.0


 

Conclusion : try the the above program by yourself and comment down below if you have any queries



Post a Comment

0 Comments