Python Tutorial (33) - Example: Calculate the sum of the cubes of n natural numbers

Time: Column:Python views:247

Calculation of the Formula: 13+23+33+43++n31^3 + 2^3 + 3^3 + 4^3 + \dots + n^3

The following Python code demonstrates how to calculate the sum of cubes of the first nn numbers, following the formula:

Requirement:

  • Input: n=5n = 5

  • Output: 225

  • Formula: 13+23+33+43+53=2251^3 + 2^3 + 3^3 + 4^3 + 5^3 = 225

  • Input: n=7n = 7

  • Output: 784

  • Formula: 13+23+33+43+53+63+73=7841^3 + 2^3 + 3^3 + 4^3 + 5^3 + 6^3 + 7^3 = 784

Example

# Function to calculate the sum of cubes
def sumOfSeries(n):
    total_sum = 0
    for i in range(1, n + 1):
        total_sum += i * i * i  # Cube of the current number
    return total_sum

# Call the function
n = 5
print(sumOfSeries(n))

Output

225

In this code, the function sumOfSeries(n) iterates from 1 to nn, calculates the cube of each number, and accumulates the sum. For n=5n = 5, the result is 225. Similarly, for n=7n = 7, it will return 784.