Home »
Python »
Python programs
Python program for sum of cube of first N natural numbers
Here, we will write a Python program to find the sum of cube of first N natural numbers.
Submitted by Shivang Yadav, on April 03, 2021
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
Sum of cube of first N Natural Numbers
13 + 23 + 33 + 43 + … N3
We will get the value of N as input from the user and then print the sum of cubes of the first N natural numbers.
Example:
Input:
N = 5
Output:
225
Method 1: Using Loop
A simple solution is to loop from 1 to N, and add their cubes to sumVal.
Program to find the sum of the cubes of first N natural number
# Python program for sum of the
# cubes of first N natural numbers
# Getting input from users
N = int(input("Enter value of N: "))
# calculating sum of cube
sumVal = 0
for i in range(1, N+1):
sumVal += (i*i*i)
print("Sum of cubes = ", sumVal)
Output:
RUN 1:
Enter value of N: 10
Sum of cubes = 3025
RUN 2:
Enter value of N: 12
Sum of cubes = 6084
Explanation:
In the above code, we have taken input from the user for the value of N. And then we have initialized the sumVal to 0 and looping from 1 to N, we will add the value (i3) to the sumVal. At last, printed the sumVal.
Method 2: Using mathematical formula
A direct approach to find the sum of the cubes is using the mathematical formula.
The formula is,
sum = { (N * (N+1)) / 2 }2
Program for the sum of the cubes of first N natural numbers
# Python program for sum of the
# cubes of first N natural numbers
# Getting input from user
N = int(input("Enter value of N: "))
# calculating sum of cubes
sumVal = (int)( pow(( (N * (N+1))/2 ) , 2) )
print("Sum of cubes =",sumVal)
Output:
RUN 1:
Enter value of N: 10
Sum of cubes = 3025
RUN 2:
Enter value of N: 12
Sum of cubes = 6084
Explanation:
In the above code, we have taken input from the user for the value of N. And then we have used the formula to get the sum and store it to sumVal and print it.
Python Basic Programs »