Python Program for Sum of Squares of first n natural numbers

Hello coders, in this tutorial we are going to discuss and write the code for the sum of squares of first n natural numbers using Python. Firstly, we will see the proof then we will proceed with the coding part.

Sum of the square of first n natural number using Python

Given a positive integer n., The task is to find 12 + 22 + 32 + ….. + n2

Now let’s see our program to perform the task.

For example:-

Input : n = 5
Output : 30
1 + 4 + 9 + 16 +25= 55

Input : n = 6
Output : 91

Technique 1:-

#Using Method 1
def squaresum(n) : 
  s = 0
  #Iteration from 1 to n
        for i in range(1, n+1) : 
    s = s + (i * i) 
  return s 
n = 5
print(squaresum(n)) 
 
Output:-
55

 

Method 2:-

Using the formula

Sum of square of first n natural numbers = (n*(n+1)*(2*n+1))/6

Example:-

When n=4

Then, sum=(4*5*9)/6

sum=30

Code for technique 2:-

#Using Method 2
def squaresum(n) : 
  return (n * (n + 1) * (2 * n + 1)) // 6
 
n = 4
print(squaresum(n)) 
                               
Output:-
30

 

Leave a Reply

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