![]() |
VOOZH | about |
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.
The most efficient solution is to use the direct mathematical formula:
Sum of cubes upto n
Example:
225
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:
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.
A generator expression allows us to generate cubes and sum them in a single, memory-efficient line.
Example:
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.
In this approach, we will use the enumerate list to find the cube sum of n natural numbers in single line.
Example:
225
Explanation: