Doubt in exercise with factorial and large numbers

Asked

Viewed 177 times

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.

  • What error are you having? Is there any message? I, particularly, did not understand your doubt...

  • 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.

  • 3

    @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 :-)

  • 1

    Thanks @hkotsubo, now that I said I realized it’s simpler like this. Thanks!

  • What is the definition of x? You do if (x < 1){ but there is no assignment to such a variable.

  • The right one was if (valorX<1). I should review my codes more before posting them here...

Show 2 more comments

2 answers

3

Problem 1: You have to do the floating point math, otherwise the x/y split result when x < y will be 0.

Problem 2: The "result" variable needs to be initialized.

I did a test (well) fast, it seems to be working.

#include <stdio.h>

int main()
{
  //VARIAVEIS
  double valorX, cont = 3, contPotencia = 1, fat = 2, potencia, x;
  float divisao, resultado = 0;

  //INICIO
  printf("Insira X: ");
  scanf("%lf", &valorX);

  // if (x < 1){ // <------ erro
  if (valorX < 1) {
    printf("Número inválido, insira um maior que 0.");
  }
  else {
    printf("Y = %lf", valorX);
    x = valorX;
    do {
      x = valorX*x;
      printf(" + %lf/%lf ", x, fat);
      contPotencia++;

      fat = cont*fat;
      cont++;

      divisao = x/fat;
      printf("\n*");
      printf("\n* x=%lf fat=%lf divisao=%f", x, fat, divisao);

      resultado = resultado+divisao;
      printf("\n* resultado: %f", resultado);

    } while (contPotencia <= 3);
  }

  printf("\n*");
  printf("\nY = %f", resultado);
}

Testing:

$ 380126.exe                                           
Insira X: 2                                            
Y = 2.000000 + 4.000000/2.000000                       
*                                                      
* x=4.000000 fat=6.000000 divisao=0.666667             
* resultado: 0.666667 + 8.000000/6.000000              
*                                                      
* x=8.000000 fat=24.000000 divisao=0.333333            
* resultado: 1.000000 + 16.000000/24.000000            
*                                                      
* x=16.000000 fat=120.000000 divisao=0.133333          
* resultado: 1.133333                                  
*                                                      
Y = 1.133333                                           

$                                                      
  • Dude, I made a mistake and I made a legal mess in the post, sorry. I posted my test code by accident, with the contPotency <= 3 to make it easier to check the result. I understood your code and it really worked for a small sequence of numbers, but the problem is that the exercise asks for the first 15 terms. That is, there comes a time when the numbers start to get so big that the result goes wrong. That’s why I used long long int. So I think the problem is exactly in the type of variables.

  • up to 17! should fit in a double...if you need to, use a long double instead of double

  • use a "long double" instead of "double" (also adapting the %lf format to %Lf in the printf) (the previous comment I made is incomplete and wrong)

  • ops, answering now another question I could see that in this case you don’t even need to use long double, using only double jpa is enough

0


I was able to answer the exercise and arrive at the expected result. The problem was in the very order of operations.

#include <stdio.h>
#include <math.h>

int main(){
    //VARIAVEIS
    unsigned long long int valorX, cont = 3, contPotencia = 1;
    float divisao, resultado, fat = 2, x;

     //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;
        resultado = x;
        do {
            x = valorX*x;
            printf(" + %.f/%.f", x, fat);

             divisao = x/fat;

            fat = cont*fat;

            contPotencia++;
            cont++;

            resultado = resultado+divisao;

        } while (contPotencia < 15);
    }
    printf("\nResultado = %f", resultado);

}

Browser other questions tagged

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