In this post, We will see how to write a python program for finding Sum of cubes of first n natural numbers in different ways.
Example:
Input: N = 2 Output: 1 * 1 * 1 + 2 * 2 *2 => 9 OR 13 + 2 3 => 9 Input: N = 3 Output: 1 * 1 * 1 + 2 * 2 * 2 + 3 * 3 * 3 => 36 OR 13 + 2 3 + 3 3 => 36
Now, Let’s see the codes:
Code 1: Run a loop from 2 to N and for each i, find i 3 and adding to the sum.
# code: 1 # first 5 natural numbers N = 5 # initialize variable with 1 sumCube = 1 # loop from 2 to N for i in range(2, N + 1) : # cube summation sumCube += i ** 3 # print the result print("Sum of Cubes of first", N , "Natural Numbers:",sumCube)
Output:
Sum of Cubes of first 5 Natural Numbers: 225.0
Code 2: Create user defined function, main and then apply the previous code logic.
# code: 2 # Define a user defined # function for finding # sum of cubes of 1st # N natural Numbers def sumOfCubes(Num) : # initialize variable with 1 sumCube = 1 # loop from 2 to N for i in range(2, Num + 1) : # Cube summation sumCube += i ** 3 # return result return sumCube # main code if __name__ == "__main__" : # first 5 natural numbers Num = 5 # function calling and # printing the result print("Sum of Cubes of first", Num , "Natural Numbers:", sumOfCubes(Num))
Output:
Sum of Cubes of first 5 Natural Numbers: 225.0
Code 3: Run a loop from 2 to N and for each i, find i * i * i and adding to the sum.
# code: 3 # Define a user defined # function for finding # sum of cubes of 1st # N natural Numbers def sumOfCubes(Num) : # initialize variable with 1 sumCube = 1 # loop from 2 to N for i in range(2, Num + 1) : # Cube summation sumCube += i * i * i # return result return sumCube # main code if __name__ == "__main__" : # first 5 natural numbers Num = 5 # function calling and # printing the result print("Sum of Cubes of first", Num , "Natural Numbers:", sumOfCubes(Num))
Output:
Sum of Cubes of first 5 Natural Numbers: 225.0
Code 4: By Using given formula :
sum of the cubes of 1st N Natural numbers: ((N) * (N + 1) / 2 ) 2
# code: 4 # Define a user defined # function for finding # sum of cubes of 1st # N natural Numbers def sumOfCubes(Num) : # return result return ((Num) * (Num + 1) / 2 ) ** 2 # main code if __name__ == "__main__" : # first 5 natural numbers Num = 5 # function calling and # printing the result print("Sum of Cubes of first", Num , "Natural Numbers:", sumOfCubes(Num))
Output:
Sum of Cubes of first 5 Natural Numbers: 225.0
Code 5: By making a anonymous function.
# code: 5 # Define a annonymous # function for returning # sum of cubes of 1st # N natural Numbers sumOfCubes = lambda Num : ((Num) * (Num + 1) / 2 ) ** 2 # main code if __name__ == "__main__" : # first 5 natural numbers Num = 5 # function calling and # printing the result print("Sum of Cubes of first", Num , "Natural Numbers:", sumOfCubes(Num))
Output:
Sum of Cubes of first 5 Natural Numbers: 225.0