Given a number n, we need to find the sum of cubes of the first n natural numbers.
Example:
Input: n = 5
Output: 225
Explanation: 13 + 23 + 33 + 43 + 53 = 225
Below are some of the ways to do it.
Using Mathematical Formula:
The most efficient solution is to use the direct mathematical formula:
Sum of cubes upto n
Example:
n = 5
res = ((n * (n + 1)) // 2) ** 2
print(res)
Output
225
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.
Example:
n = 5
sum = 0
for i in range(1, n + 1):
res += i ** 3
print(res)
Output
225
Explanation: We use a simple loop to add the cube of each number to res. This method is easy to understand but less efficient than the formula.
Using Generator Expression
A generator expression allows us to generate cubes and sum them in a single, memory-efficient line.
Example:
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 single line.
Example:
n = 5
res = sum([(i+1) ** 3 for i, _ in enumerate(range(n))])
print(res)
Output
225
Explanation:
- enumerate(range(n)): returns pairs (index, value) where:
index starts from 0
value is each number from 0 to n-1 - (i + 1) ** 3: gives the cube of each natural number from 1 to n
- sum(): adds up all cubes.