Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

factorial method resulting in error

Tags:

c#

factorial

I'm trying to get the factorial value of number 66, but my method resulting me an output 0. But whenever I try to get the factorial of 5, it is resulting me an output 120. Could anyone please tell me why?

 public static int factorial(int n)
 {
            if (n == 1)
                return n;
            return n * factorial(n - 1);
 }
like image 374
Dusk Avatar asked Nov 30 '22 09:11

Dusk


1 Answers

Sure - factorials get very big, very fast. You're overflowing the bounds of int very quickly... and at some point you'll have multiplied by enough factors to get an overflow to 0, which will then keep the value at 0 forever.

According to a quick Google search, 66 factorial is 5.44344939 × 1092 - which is considerably more than int can handle, or even long or decimal. You could get double to handle it - you'd lose a huge amount of precision, and that would accumulate really quickly too, but at least it wouldn't overflow...

like image 171
Jon Skeet Avatar answered Dec 19 '22 04:12

Jon Skeet