Write a Python Program to calculate Sum of Series 1³+2³+3³+….+n³ using For Loop and Functions with an example.
The Mathematical formula for Python Sum of series 1³+2³+3³+….+n³ = ( n (n+1) / 6)²
Python Program to calculate Sum of Series 1³+2³+3³+….+n³
This Python program allows users to enter any positive integer. Next, the Python finds the sum of series 1³+2³+3³+….+n³ using the above formula.
# Python Program to calculate Sum of Series 1³+2³+3³+….+n³
import math
number = int(input("Please Enter any Positive Number : "))
total = 0
total = math.pow((number * (number + 1)) /2, 2)
print("The Sum of Series upto {0} = {1}".format(number, total))
Python Sum of Series 1³+2³+3³+….+n³ using math pow output
Please Enter any Positive Number : 7
The Sum of Series upto 7 = 784.0
Sum = pow (((Number * (Number + 1)) / 2), 2)
= pow (((7 * (7 + 1)) / 2), 2)
Sum = pow (((7 * 8) / 2), 2) = 784
Python Program to calculate Sum of Series 1³+2³+3³+….+n³ Example 2
If you want the Python to display the Series 1³+2³+3³+….+n³ order, we have to add extra For Loop along with If Else.
import math
number = int(input("Please Enter any Positive Number : "))
total = 0
total = math.pow((number * (number + 1)) /2, 2)
for i in range(1, number + 1):
if(i != number):
print("%d^3 + " %i, end = ' ')
else:
print("{0}^3 = {1}".format(i, total))
Python Sum of Series 1³+2³+3³+….+n³ output
Please Enter any Positive Number : 5
1^3 + 2^3 + 3^3 + 4^3 + 5^3 = 225.0
Python Program to calculate Sum of Series 1³+2³+3³+….+n³ using Functions
This Python Sum of Series 1³+2³+3³+….+n³ program is the same as above. However, in this Python program, we are defining a function to place logic.
import math
def sum_of_cubes_series(number):
total = 0
total = math.pow((number * (number + 1)) /2, 2)
for i in range(1, number + 1):
if(i != number):
print("%d^3 + " %i, end = ' ')
else:
print("{0}^3 = {1}".format(i, total))
num = int(input("Please Enter any Positive Number : "))
sum_of_cubes_series(num)
Please Enter any Positive Number : 7
1^3 + 2^3 + 3^3 + 4^3 + 5^3 + 6^3 + 7^3 = 784.0
Python Program to find Sum of Series 1³+2³+3³+….+n³ using Recursion
Here, we are using the Python Recursive function to find the Sum of Series 1³+2³+3³+….+n³.
def sum_of_cubes_series(number):
if(number == 0):
return 0
else:
return (number * number * number) + sum_of_cubes_series(number - 1)
num = int(input("Please Enter any Positive Number : "))
total = sum_of_cubes_series(num)
print("The Sum of Series upto {0} = {1}".format(num, total))
