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. By Shivang Yadav Last updated : April 14, 2023

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.

The sum of cubes of first N natural numbers is the result of 13 + 23 + 33 + 43 + … N3.

Problem statement

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

Sum of Cube of First N Natural Numbers

There are two different approaches to find the sum of cubes of first N natural numbers – The first one is by using the loop in which you can find the cube of each number and then find the sum of the cubes, and the second approach is using the mathematical formula. Let's discuss them in detail.

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 »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.