This Python tutorial gives an easy way to find the sum of cubes of first n natural numbers i.e., 1*1*1+2*2*2+3*3*3+.....n*n*n.
We often find it interesting to code the problems which we have studied in our school. One such problem is to find the sum of cubes for given 'n' natural numbers.
It is always fun to make your machine work instead of using our own brain.
Input : n=4
Output : 100
Because 13+23+33+43=1+8+27+64=100.
There are two ways to code this problem.
1. Brute force approach.
2. Formula-based approach.
Let us see the both in detail.
1. Brute force approach :
1. Initialize a variable sum to 0 i.e., sum=0;
2. Use a loop and keep incrementing a variable from 1 to n.
3. Add it's cube to the sum in the consecutive step.
4. Print the sum after the loop ends.
n=int(input("Enter a natural number")) sum=0 for i in range(1,n+1): sum=sum+i*i*i print(sum)
Look at the Python code above.
2. Formula-based approach :
1. To get the sum of cubes of n natural numbers ,we can use the following formula :
sum=(n*(n+1)/2)2
2. Then, print the sum.
n=int(input("Enter a natural number")) sum=pow((n*(n+1)/2),2) print(int(sum))
Hope it helped!
Submitted by MOKSHITHA CHANDAMPETA (mokshithamini24)
Download packets of source code on Coders Packet
Comments