Python Program to Sum of squares of first n natural numbers

Python program to calculate sum of squares of first n natural numbers; Through this tutorial, i am going to show you how to find sum of squares of first n natural numbers in python using for loop and mathematical formula.

Python Program To Sum of squares of first n natural numbers

  • Python program to find sum of squares of first n natural numbers using for loop
  • Python program to find sum of squares of first n natural numbers using mathmatic formula

Python program to find sum of squares of first n natural numbers using for loop

Use the following steps and write a program to find the sum of squares of the first n natural numbers:

  • Get input number from the user
  • Calculate the sum of square of given N number using for loop
  • Print sum of square of n given number
# Python program for sum of the 
# square of first N natural numbers
# Getting input from users
N = int(input("Enter value of N: "))
# calculating sum of square 
sumVal = 0
for i in range(1, N+1):
    sumVal += (i*i)
print("Sum of squares = ", sumVal)

Output

Enter value of N: 10
Sum of squares =  385

Python program to find sum of squares of first n natural numbers using mathmatic formula

Use the following steps and write a program to find the sum of squares of the first n natural numbers:

  • Get input number from the user
  • Calculate the sum of square of the n given number using mathmatic formula
  • Print sum of square of n given number
# Python program for sum of the 
# square of first N natural numbers
# Getting input from user
N = int(input("Enter value of N: "))
# calculating sum of square 
sumVal =  (int)( (N * (N+1) * ((2*N) + 1))/6 )
print("Sum of squares =",sumVal)

Output

Enter value of N: 12
Sum of squares =  650

Recommended Python Programs

Leave a Comment