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

Asked

Viewed 485 times

3

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 was able to solve it, but there’s probably some way I can spend a lot less lines. It’s 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

1 answer

4


If you look at 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. Just like you did in the first repetition.

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

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

Think about this, if you have a formula that uses values from 1 a n, How many repetition blocks do you need? In this case, 1 only. Try to do the calculation on the same repetition block (ie using only 1 "while").

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

So if I have 4!, to calculate 5! I only 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 in your code.

Another tip: You are using 3 "while" in your code, where only 1 is required, try to do with only 1, and for each iteration, you calculate each of the summation portions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.