This Python program reads a number n from the user and calculates the sum of the following mathematical series:
1/1! + 2/2! + 3/3! + ... + n/n!
It uses a method to compute factorials and a loop to accumulate the total sum.
This exercise helps reinforce concepts of loops, factorials, and floating-point precision.
def factorial(num: int) -> int:
result = 1
for i in range(2, num + 1):
result *= i
return result
def series_sum(n: int) -> float:
total = 0.0
for i in range(1, n + 1):
total += i / factorial(i)
return total
# Read input from user
n = int(input("Enter a number n: "))
total = series_sum(n)
print(f"The result of the series up to {n} is: {total:.6f}")
The result of the series up to 4 is: 5.000000
- The user enters a number n
- The factorial method computes each factorial from 1 to n
- The series_sum method calculates each term i / i! and adds it to the total
- The final result is printed with six decimal places for precision