I have the following function:
private static BigInteger Factorial(int number)
{
if(number < 2) return BigInteger.One;
double sum = 0;
for(int i = 2; i < number; i++)
sum += Math.Log(i);
return new BigInteger(Math.Exp(sum));
}
This works fine for small input numbers like 10
, however if I pass a bigger number like 50000
it crashes and throws an OverflowException
.
I understand why this is happening, the result of Math.Exp(sum)
is just too big for a double
. But that's why I'm trying to use BigInteger
after all, to avoid these type of exceptions.
The problem is that wrapping the result like new BigInteger(Math.Exp(sum))
is useless because Map.Exp(sum)
is trying to return a double
anyway.
So I decided to use BigInteger.Pow
static function:
return BigInteger.Pow(new BigInteger(Math.E), number);
Note the new BigInteger(Math.E)
part. BigInteger.Pow
takes a BigInteger
as the first parameter so I don't have a choice but to wrap my Math.E
to a BigInteger
.
However, by doing this I am actually truncating the decimal part of my Math.E
which ruins my algorithm because I end up with a totally different result.
I was looking for something like BigDouble
or something similar, but the only class that I seem to find is BigInteger
.
How can I successfully return the correct result as a BigInteger
on this function and at the same time have an exception-safe code when big input is received?