Python Program for cube sum of first n natural numbers

PythonServer Side ProgrammingProgramming

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

Problem statement −Given an input n, we need to print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term.

Here we will discuss two approach to reach the solution of the problem statement −

  • Brute-force approach using loops.
  • Mathematical solution of sum of n numbers.

Approach 1 −Computing sum of each term by adding by iterating over the numbers

Example

 Live Demo

def sumOfSeries(n):
   sum = 0
   for i in range(1, n+1):
      sum +=i*i*i
   return sum
# Driver Function
n = 3
print(sumOfSeries(n))

Output

36

Approach 2 −Computation using mathematical formula

Here we will be using mathematical sum formulae which is aldready derived for the cubic sum of natural numbers.

Sum = ( n * (n + 1) / 2 ) ** 2

Example

 Live Demo

def sumOfSeries(n):
   x = (n * (n + 1) / 2)
   return (int)(x * x)
# main
n = 3
print(sumOfSeries(n))

Output

36

Conclusion

In this article, we learned about the approach to compute the cube sum of first n natural numbers.

raja
Published on 25-Sep-2019 13:16:16
Advertisements