Sum of Cubes of First N Natural Numbers


Sum of Cubes of First N Natural Numbers

To find the sum of cubes of first N natural numbers, read the value of N from user using input(), then iterate from 1 to N using a For Loop, find cube of each number, and accumulate it in a variable, say sum sum, over the iterations.

The sum of cubes of first N natural numbers is

sum = 13 + 23 + 33 + . . . + n3

If you are good in remembering formula or remembering that there is a formula, then the following will help you in finding the sum of cubes of first n natural numbers.

(n(n + 1)/2)2

We shall go through two of these methods in finding the sum of cubes of first n natural numbers using Python.

1. Program using For Loop

In the following program, we shall define a function sumOfCubes() that takes n as argument, use For Loop to compute the sum of cubes, and then return the sum.

We read n from user, call sumOfCubes() with the n passed as argument.

Input

n, where n > 0

Python Program

def sumOfCubes(n) :
    if n < 0:
        return
    sum = 0
    for i in range(n+1):
        sum += pow(i, 3)
    return sum

n = int(input('Enter n : '))
sum = sumOfCubes(n)
print(f'Sum : {sum}')

Output

Enter n : 4
Sum : 100

Important Points regarding above program

2. Program using Formula

In the following program, we shall define a function sumOfCubes() that takes n as argument, uses the following formula to compute the sum of cubes, and then return the sum.

(n(n + 1)/2)2

We read n from user, call sumOfCubes() with the n passed as argument.

Input

n, where n > 0

Python Program

def sumOfCubes(n) :
    if n < 0:
        return
    sum = pow(n * (n + 1) / 2, 2) 
    return int(sum)

n = int(input('Enter n : '))
sum = sumOfCubes(n)
print(f'Sum : {sum}')

Output

Enter n : 4
Sum : 100

Since we have division operation in the formula, Python implicitly typecasts the value to floating-point number. We may convert the float to int using int() function.