Domanda

I wrote some code to calculate the result of 100!, but my function stops giving the correct answer after 22! Here's my code. The assignment was to calculate the sum of the digits of 100!, but my code giver incorrect answers after 22!

/*Calculates the factorial of a given number*/
double factorial(double num);

/*Calculates how many digits are in a number*/
int num_digits(double num);

int main (int argc, char *argv[]) {
  double ans = factorial(23);
  int num = num_digits(ans);

  printf("%lf\n", ans);
  printf("%d\n", num);
  char x[num];

  //convert the number returned by factorial() to a char array
  sprintf (x, "%lf", ans);

  int i = 0;
  int sum= 0;

  for (i = 0; i < num; i ++) {
    sum += x[i] - '0';
  }

  printf("--\n%d\n", sum);


  return 0;
}

double factorial(double num) {
  int i;
  double sum = 1;

  /*heel simpel, gwn 1 x sum, sum * sum - 1 enz..*/
  for (i = num; i > 0; i --) {
    sum *= i;
  }

  return sum;
}
È stato utile?

Soluzione

22! is about 10^21, which is about 2^63. This means, you can calculate 22! on a 64 bit machine using normal arithmetic, but not more because then you would get an integer overflow, and the result is garbage. You had to use a special library that provides arithmetic with larger numbers.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top