Coders Packet

Python program to find sum of the squares of first n natural numbers.

By MOKSHITHA CHANDAMPETA

This Python tutorial gives an easy way to find the sum of squares of first n natural numbers i.e., 1*1+2*2+3*3+......n*n.

We often find it interesting to code the problems which we have studied in our school. One such problem is to find the sum of squares for given 'n' natural numbers.

It is always fun to make your machine work instead of using our own brain.

Input : n=5

Output : 55

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

There are two ways to code this problem.

1. Brute force approach.

2. Formula-based approach.

Let us see the both in detail.

1. Brute force approach :

1. Initialize a variable sum to 0 i.e., sum=0;

2. Use a loop and keep incrementing a variable from 1 to n.

3. Add it's square to the sum in the consecutive step.

4. Print the sum after the loop ends.

n=int(input("Enter a natural number"))
sum=0
for i in range(1,n+1):
    sum=sum+i*i
print(sum)

2. Formula-based approach :

1. To get the sum of squares of n natural numbers ,we can use the following formula :

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

2. Then, print the sum.

n=int(input("Enter a natural number"))
sum=n*(n+1)*(2*n+1)/6
print(int(sum))

Hope it helped!

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by MOKSHITHA CHANDAMPETA (mokshithamini24)

Download packets of source code on Coders Packet