0

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);
}
user13863346
  • 327
  • 2
  • 11
  • 1
    While C **allows** you to write `int unsigned long`, a seasoned programmer never writes that, using instead `unsigned long`, or `unsigned long int`. – Antti Haapala -- Слава Україні Jul 04 '20 at 08:28
  • a tip about naming: when using single letter variables, avoid variables that may suggest the wrong type name. For example, the name `f` might lead you to think of the variable as a `float`. As your code becomes longer or more complex, these things become more important. – Myst Jul 04 '20 at 08:31
  • How do you know you got the correct output when you calculate 65! ? – M. Nejat Aydin Jul 04 '20 at 08:35
  • @M.NejatAydin Your right, my value for factorial 65 generated by my code is 9223372036854775808 , very off from the real value. – user13863346 Jul 04 '20 at 09:12

2 Answers2

2

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

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

Adding on to @JohnZwinck, the maximum value for a variable of type unsigned long long (ULLONG_MAX) is 18446744073709551615. So all the values greater than 20! are going to have a garbage value

You can refer to this for more information.

Sai Sreenivas
  • 1,690
  • 1
  • 7
  • 16