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

3

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

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

So far what I did was 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 not get out of it.

edit

I think I've managed to figure it out, but there's probably some way I can spend a lot fewer rows. It looks 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
    
asked by anonymous 12.09.2018 / 19:37

1 answer

4

If you observe the formula:

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

Note that only 1 repetition is required which iterates all values from 1 to n . Just like you did in the first repetition.

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

So you would not need a second replay, that's where you might be getting confused.

Consider the following, if you have a formula that uses values from 1 to n , how many repetition blocks do you need? In this case, 1 only. Try to make the calculation in the same block of repetition (ie using only 1 "while").

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

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

The calculation is much simpler than you 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 required, try to do with only 1, and for each iteration you calculate each of the sum portions.

    
12.09.2018 / 19:51