Python Program for cube sum of first n natural numbers (original) (raw)

Last Updated : 30 Oct, 2025

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 = \left( \frac{n(n + 1)}{2} \right)^2

**Example:

Python `

n = 5 res = ((n * (n + 1)) // 2) ** 2 print(res)

`

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:

Python `

n = 5 sum = 0

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

print(res)

`

**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:

Python `

n = 5

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

print(res)

`

**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:

Python `

n = 5 res = sum([(i+1) ** 3 for i, _ in enumerate(range(n))]) print(res)

`

**Explanation: