Search code examples
cfactorial

Factorial calculation is not right in my C program?


#include <stdio.h>
#include <conio.h>

int main()
{
  long signed fact=1;

  int c, n ;

  printf("Factorial to be calculated: ");
  scanf("%d", &n);

  for (c = 1; c <= n; c++)
  fact = fact * c;

  printf("Factorial of %d = %ld\n", n, fact);
  getch();
  return 0;
}

In the C program above, when I run, I can not get 13! correct. It's output is true for 12. How can I fix this? I thought long unsigned will be enough for 13.


Solution

  • It's possible that long is 32-bit on your platform (you can find out by printing the value of sizeof(long)). 13! is greater than 2^32-1 (the largest possible value for a 32-bit unsigned value), so it overflows.

    Try using uint64_t (from <stdint.h>) instead.