Search code examples
cfactorial

C Programming factorial outputting wrong values


int main (void)
{
   int i;
   for (i=1; i<=20; i++) {
       int j;
       unsigned long long fac = 1;

       for ( j = 1; j<=i; ++j) {
          fac *= j;
       }

       printf ("%2i! = %ld\n", i, fac);
    }

return 0;
}

From 14! to 20! outputs wrong values.

It either gives a negative number or the number is not big enough.. what is the problem?


Solution

  • printf ("%2i! = %ld\n", i, fac);
    

    The problem is here, use proper notation for unsigned long long type value

    Try:

    printf ("%2i! = %llu\n", i, fac);