Python Program for cube sum of first n natural numbers

In this article, we will learn to find the sum of the cube of the first n number using the python program.

the sum of the cube of n numbers:

13 + 23 + 33 + 43 + ....... + (n-1)3 + n3



We find the sum of the cube of positive numbers from 1 to nth using two method

  • using for loop
  • using mathematically



Method 1: Using for loop

Time Complexity for this program is: O(N)

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Sum of the cube of positive numbers from 1 to nth using forloop
n = int(input("Enter nth number: "))
sum = 0

for i in range(1,n+1):
    sum = sum + (i*i*i)

print("Sum of the cube of the number from 1 to",n,"is: ",sum)

# Sum of the cube of positive numbers from of nth using forloop - docodehere.com

Output

Enter nth number: 10
Sum of the cube of the number from 1 to 10 is:  3025



Method 2: Using Mathematical formula

Time Complexity for this program is: O(1)

Program

1
2
3
4
5
6
# Sum of the cube of positive numbers from 1 to nth without forloop
n = int(input("Enter nth number: "))

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

# Sum of the cube of positive numbers from of nth without forloop - docodehere.com

Output

Enter nth number: 3
36
Next Post Previous Post
No Comment
Add Comment
comment url