The task:

For this natural n, calculate the sum of 1! +2! +3! + ... + n !. In solving this problem, you can use only one cycle. The use of math math library in this problem is prohibited.

n = int(input()) N = 1 sum = 0 for a in range(1, n+1): for b in range(1, a+1): N = N * b sum += N print(sum) 

However, my decision does not come out. Tell me how to solve it correctly?

  • If cycles are not possible, then recursion in the help - Vitaly Shebanits pm

2 answers 2

If the input is given only natural n , then you can:

 n = int(input()) sum_of_factorials = 1 curr_factorial = 1 for i in range(2, n + 1): curr_factorial *= i sum_of_factorials += n print(sum_of_factorials) 

(You need 1!+2!+3!+...+n! Or are you not sealed? If not, just sum_of_factorials just sum_of_factorials by 2 at the end and subtract 1 ).

This is a very simple dynamic programming. You do not need to re-evaluate the curr_factorial each time to add it, because the current curr_factorial is just the old value, multiplied by the number of the current iteration cycle.

     n = int(input()) suma = 0 previous = 1 # ΠŸΡ€Π΅Π΄Ρ‹Π΄ΡƒΡ‰ΠΈΠΉ Ρ„Π°ΠΊΡ‚ΠΎΡ€ΠΈΠ°Π» for i in range(1, n + 1): current = previous * i # Π’Π΅ΠΊΡƒΡ‰ΠΈΠΉ Ρ„Π°ΠΊΡ‚ΠΎΡ€ΠΈΠ°Π» - см. ΠΏΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅ послС ΠΊΠΎΠ΄Π° suma += current previous = current print(suma) 

    Here we use the fact that the factorial of a number is equal to the factorial of the previous number multiplied by the current number β€” for example, 5! == 4! * 5 5! == 4! * 5 5! == 4! * 5 because

      5! == 1 * 2 * 3 * 4 * 5 == (1 * 2 * 3 * 4) * 5 == 4! * 5