1
I need to do an exercise that asks for the Y value given by Y = x + x 2/2! + x 3/3! + x 4/4! + ... , considering the first 15 terms. I’m having problems because the factorial results from the 10 term already start to become giant. For this, I used long long int. I BELIEVE this is part of of(operations) that is wrong, because I tried to change the countPotency to <= 3, and tested the program by putting x = 2 and the result would have to be 6. Even so, gave an absurd number of great. What may be happening may also be the types of variables are wrong, but I don’t know what else to try to fix it.
#include <stdio.h>
int main()
{
//VARIAVEIS
unsigned long long int valorX, cont = 3, contPotencia = 1, fat = 2, potencia, x;
float divisao, resultado;
//INICIO
printf("Insira X: ");
scanf("%llu", &valorX);
if (valorX < 1){
printf("Número inválido, insira um maior que 0.");
}
else {
printf("Y = %llu", valorX);
x = valorX;
do {
x = valorX*x;
printf(" + %llu/%llu ", x, fat);
contPotencia++;
fat = cont*fat;
cont++;
divisao = x/fat;
resultado = resultado+divisao;
} while (contPotencia < 15);
}
printf("\nY = %f", resultado);
}
I think it would look better if you did a recursive function to calculate the factorial.
– WhoisMatt
What error are you having? Is there any message? I, particularly, did not understand your doubt...
– Leonardo Alves Machado
My question is whether the part of the operations is wrong or the types of data I used to declare the variables. It’s just that since I’m working with big numbers, that could be it. But I believe that’s part of the operation itself... I just don’t know what to fix.
– Karina
@Whoismatt In this case you don’t need a function just to calculate the factorial. In the first term the denominator is 1!, in the second is 2!, in the third is 3!, etc., so just keep the previous value and each iteration, multiply by the next value (something thus). And if you still want a separate function, a loop is much more efficient (and simple) to calculate factorial than recursion :-)
– hkotsubo
Thanks @hkotsubo, now that I said I realized it’s simpler like this. Thanks!
– WhoisMatt
What is the definition of x? You do if (x < 1){ but there is no assignment to such a variable.
– anonimo
The right one was if (valorX<1). I should review my codes more before posting them here...
– Karina