Reputation: 617
factorial program using recursion in C:
long fact(int n)
{
if (n == 1)
return 1;
else
{
return n*fact(n - 1);
}
}
The program works perfectly for numbers up to 12. But for numbers bigger than that the fact gives a wrong value.
The range of long is sufficient for such numbers then what is the reason that factorial is not getting calculated for the numbers greater than 12?
Upvotes: 0
Views: 1656
Reputation: 122363
The range of
long
is sufficient for such numbers
No, that's not always true. long
is only guaranteed to be at least 32-bit, but the value of 13!
is 6227020800
, or 0x17328CC00
, which can not be held in a 32-bit integer.
Try using long long
instead.
Upvotes: 1