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);
}
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...
Your method overflows. See the following example:
static void Main(string[] args)
{
Console.WriteLine(factorial(66));
}
public static int factorial(int n)
{
if (n == 1)
return n;
var result = n * factorial(n - 1);
Console.WriteLine("{0} : {1}", n, result);
return result;
}
With this example, the results of each iteration is printed.
You see that at one point, result becomes 0
and this means that every iteration from that point on becomes n * 0
.
You can try using BigInteger
. This will give the correct result. Calculate factorials in C# contains more information on this.
66! does not fit into an int
. Use BigInteger
.
The problem is that the factorial of 66 is way to large to fit into an int
. I think it will also we way to large to fit into a long
.
As an example, factorial(20)
will return 2432902008176640000
The factorial of 50 is 3.0414093202×1064 which exeeds already what a int can contain.
Use long
or BigInteger
for this.
You get numeric overflow, 66! ~= 5e92 which is way larger than an int
can handle. Also, factorials are better calculated using a for loop.
Approximately 13 or 14 is the largest number whose factorial fits in an int... If you switch to long, it'll be aroung 18 or 19 if I recall correctly. If you wish arbitraty big numbers you'd have to write your own big arithmetic library or use an existing one :)
You need to use the appropriate data type.
In this case the Big Integer data type is probably best seeing as how fast the numbers get real big.
Here is the way you use this data type.
Right click on your project, choose the add reference menu.
Look for the system.numerics library and add it.
You then add the using clause in your code.
And then you can initialise variable with the keyword as usual.
来源:https://stackoverflow.com/questions/4202626/factorial-method-resulting-in-error