Search code examples
cintlong-integerfactorialunsigned-integer

Unable to calculate factorial , getting output as 0 in C


Tried calculating factorial of 65, got correct output. Anything greater than 65 results in output of 0. Shocking since I'm using unsigned long int. What is amiss ?

Code:

#include <stdio.h>

void factorial(int unsigned long);
int main()
{
    int unsigned long num, result;
    printf("\nEnter number to obtain factorial : ");
    scanf("%ld", &num);
    factorial(num);
}
void factorial (int unsigned long x)
{
    register int unsigned long f = 1;
    register int unsigned long i;
    for (i=x;i>=1;i--)
        f= f*i;
    printf("\nFactorial of %lu = %lu\n",x,f);
}

Solution

  • You certainly did not get the correct result for 65! log2(65!) is just over 302 bits (Google it), so you'd need a long int of at least 303 bits to calculate that correctly. There is no computer in the world where long int is over 300 bits (let's see how this answer ages!).

    The largest factorial you can compute in 64 bits is 20! (which is about 2.4e18).