Python Program for cube sum of first n natural numbers
We are given a number n and we need to print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till the n-th term in python.
Examples:
Input: n = 5
Output: 225
Explanation: 13 + 23 + 33 + 43 + 53 = 225
Let’s discuss some of the ways to do it.
Using Mathematical Formula:
Most efficient solution is to use the direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2, where n is the number of terms.
n = 5
res = ((n * (n + 1)) // 2) ** 2
print(res)
Output
225
Explanation: ((n * (n + 1)) // 2) ** 2 gives us the sum of cubes of integers from 1 to n.
Using Brute Force approach
We can iterate from 1 to n, computing the cube of each number and summing them, where n is the limit up to which the sum is required.
n = 5
sum = 0
for i in range(1, n + 1):
res += i ** 3
print(res)
Output
225
Explanation: iterate from 1 to n using for loop and sum += i**3, keeps on adding the the cubes of the numbers.
Using generator expression
Use generator expression to generate a list of cubes for numbers from 1 to n, then apply the sum() function to get the total. This approach is concise and efficient, combining iteration and summation in a single line.
n = 5
res = sum(i**3 for i in range(1, n + 1))
print(res)
Output
225
Explanation: i**3 for i in range(1, n + 1) creates a list of cubes of numbers from 1 to n and then sum() function returns the sum of all the elements inside the list.
Using Enumerate List
In this approach, we will use the enumerate list to find the cube sum of n natural numbers in one line.
n = 5
res = sum([(i+1) ** 3 for i, _ in enumerate(range(n))])
print(res)
Output
225
Explanation:
- use list comprehension with enumerate(range(n)) to generate cubes of numbers from 1 to n.
- apply the sum() function to compute the total sum of cubes.
- underscore (_) in enumerate() is a throwaway variable since enumerate(range(n)) returns both index and value, but only the index (i) is used.