Adding factorials. Given an integer n, calculate and print the sum of the factorials from 1! to n!:
|
n = int(input()) sum_factorials = 0 current_factorial = 1 for i in range(1, n + 1): current_factorial *= i sum_factorials += current_factorial print(sum_factorials) |
- Reading Input:
- The
input()
function reads a line of text from the user.
- The
int()
function converts this input to an integer and stores it in the variable n
.
- Initialize the Sum and Current Factorial:
sum_factorials = 0
current_factorial = 1
- A variable
sum_factorials
is initialized to 0. This will be used to store the sum of the factorials.
- A variable
current_factorial
is initialized to 1. This will be used to compute each factorial incrementally.
- Calculate Sum of Factorials:
for i in range(1, n + 1):
current_factorial *= i
sum_factorials += current_factorial
- A
for
loop iterates over the range from 1 to nnn (inclusive).
- In each iteration, the current number iii is multiplied with
current_factorial
to compute the factorial incrementally.
- The
current_factorial
is then added to sum_factorials
.
- Print the Sum of Factorials:
- Finally, the
print()
function outputs the value of sum_factorials
.