Exercise algorithm given the values of real X and natural positive N, calculate

Given the values of x real and n natural positive, calculate:

S = (x+1)/1! + (x+2)/2! + (x+3)/3! + ... + (x+n)/n!

So far what I've done is this:

leia x
leia n
nFatorial = 1    
contadorFatorial = 0
enquanto contadorFatorial < n faça             */Aqui é uma funçao pra calcular fatorial
  |contadorFatorial = contadorFatorial + 1
  |nFatorial = nFatorial * contadorFatorial
fim enquanto
s1 = x+1
sn = x+n/nFatorial
nFatorial2 = 1
contadorFatorial2 = 0
enquanto sn < s1 faça              
  |n = n - 1
  |enquanto contadorFatorial2 < n faça            */Calcular Fatorial
    |contadorFatorial2 = contadorFatorial2 + 1
    |nFatorial2 = nFatorial2 * contadorFatorial2

But I can't get out of it.

Edit

I think I managed to solve, but there is probably some way that spends much less lines. It looked like this:

leia x    
leia n
nFatorial = 1
contadorFatorial = 0
enquanto contadorFatorial < n faça
  |contadorFatorial = contadorFatorial + 1
  |nFatorial = nFatorial * contadorFatorial
fim enquanto
s1 = x+1
sn = (x+n)/nFatorial
soma = sn
enquanto sn < s1 faça
  |n = n - 1
  |nFatorial2 = 1
  |contadorFatorial2 = 0
  |enquanto contadorFatorial2 < n faça
    |contadorFatorial2 = contadorFatorial2 + 1
    |nFatorial2 = nFatorial2 * contadorFatorial2
  fim enquanto
  |sn2 = (x+n)/nFatorial2
  |soma = soma + sn2
  |sn = sn2
fim enquanto
escreva "o valor de S é", soma
fim
Author: RareProton, 2018-09-12

1 answers

Observe the formula:

S = (x+1)/1! + (x+2)/2! + (x+3)/3! + ... + (x+n)/n!

Note that only 1 repetition is required that iterates all values from 1 to n. Exactly as you did in the first repetition.

contadorFatorial = 0
enquanto contadorFatorial < n faça
    contadorFatorial = contadorFatorial + 1

So, you wouldn't need a second repetition, that's where you might be getting confused.

Think of this, if you have a formula that uses values from 1 to n, how many repeat blocks do you need? In this case, 1 only. Try to do the calculation in the same repeating block (i.e., using only 1 "while").

Say: Remember that X! = X * (X - 1)!

So, if I have 4!, to calculate 5! I just need to do 4! * 5, seen that: 5! = 5 * (5-1)!

The calculation is much simpler than you might think. The more repetitions you use, the more complexity you put into your code.

Another tip: You are using 3 "while" in your code, with only 1 being needed, try to do with only 1, and for each iteration you calculate each of the sum plots.

 4
Author: Rodrigo G Rodrigues, 2018-09-13 11:45:05