Python Program for Sum of squares of first n natural numbers


In this article, we will learn about the solution and approach to solve the given problem statement.

Problem statement

Given a positive integer N as input . We need to compute the value of 12 + 22 + 32 + ….. + N2.

Problem statement:This can be solved by two methods

  • Multiplication addition arithmetic
  • Using mathematical formula

Approach 1: Multiplication & Addition Arithmetic

Here we run a loop from 1 to n and for each i, 1 <= i <= n, find i2 and add to sm.

Example

 Live Demo

def sqsum(n) :
   sm = 0
   for i in range(1, n+1) :
      sm = sm + pow(i,2)
   return sm
# main
n = 5
print(sqsum(n))

Output

55

Approach 2: By using mathematical formulae

As we all know that the sum of squares of natural numbers is given by the formula −

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

Example

 Live Demo

def squaresum(n) :
   return (n * (n + 1) * (2 * n + 1)) // 6
# Driven Program
n = 10
print(squaresum(n))

Output

385

Conclusion

In this article, we learned about the approach to find the Sum of squares of first n natural numbers.

Updated on: 26-Sep-2019

577 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements