To resolve this issue you can implement two functions. One of them to calculate the factorial of the number and another to produce the summation of values.
OBSERVATION 1: Observe the layout of the sequence of signs of ADDITION and SUBTRACTION.
The sequence we were given was: S = 10/1! - 9/2! + 8/3! - ... - 1/10!
Well, to resolve this issue we can implement the following code:
def somar(n):
soma = cont = 0
for c in range(n, 0, -1):
cont += 1
termo = (c / fatorial(cont))
if cont % 2 == 0:
soma -= termo
else:
soma += termo
return round(soma, 2)
def fatorial(nu):
prod = 1
for i in range(nu, 0, -1):
prod *= i
return prod
num = int(input('Digite um número: '))
print(somar(num))
Note that when we execute this code we receive the following message: Digite um número:
. At this point we must enter a integer and press enter
.
After that, the entered value will be passed as parameter to the function sum(n). Getting there, every iteration of the block for
, the term (c / factorial(cont)).
Observation 2: With each iteration, the block if
will verify whether cont
is even. Positive case, termo
will be decreased by soma
. Negative case, termo
will be incrementado
in soma
.
Observation 3: Every iteration of the block for
of function somar(n)
, will be called the function fatorial(nu)
that calculates the factorial of the cont.
Then this term is accumulated in the variable summing up and subsequently the return of the function sum(n) will be shown.
Now, if you prefer, you can use the method factorial library Math. This way, the code would be:
from math import factorial
def somar(n):
soma = cont = 0
for c in range(n, 0, -1):
cont += 1
termo = (c / factorial(cont))
if cont % 2 == 0:
soma -= termo
else:
soma += termo
return round(soma, 2)
num = int(input('Digite um número: '))
print(somar(num))
Another way more quick to calculate this sum is:
def somar(n):
soma = cont = 0
fat = 1
for c in range(n, 0, -1):
cont += 1
fat *= cont
termo = (c / fat)
if cont % 2 == 0:
soma -= termo
else:
soma += termo
return round(soma, 2)
num = int(input('Digite um número: '))
print(somar(num))
Let’s test the codes?
After we run both codes, we can enter any integer numbers and press enter
.
In case we enter the numbers 2, 3, 4 and 10 respectively, we will have the following results:
n = 2 = (2/1!) - (1/2!) = 1.5
n = 3 = (3/1!) - (2/2!) + (1/3!) = 2.17
n = 4 = (4/1!) - (3/2!) + (2/3!) - (1/4!) = 2.79
n = 10 = (10/1!) - (9/2!) + (8/3!) - (7/4!) + (6/5!) - (5/6!) + (4/7!) - (3/8!) + (2/9!) - (1/10!) = 6.59
I believe this inner loop is doubling the sum of terms. Swap
for k in range(i, 0, -1): somar += k/fat
for:somar += (11-i) / fat
.– anonimo
Explain to me how the expected output can be
6.59
if10/1!
is equal to 10 ??? The result will certainly be greater than 10.– Paulo Marques
I realized now that there are signs of addition and subtraction. I was betrayed by the title of the question. So,
6.59
makes sense.– Paulo Marques
Typo:
!3
--3!
– JJoao