I am using BigInteger in C# in connection with the factorial function. The program has a lightning fast calculation of 5000!, but has an overflow error at 10000!. According to wolfram alpha, 10000! is approximately
10000! = 2.8 x 10^35659
From what I can tell from this post, a BigInteger is stored in an int[] array. If I interpret the int type correctly, it uses 4 bytes, meaning that 10000! uses about 4 x log10(2.8 x 10^35659) = 142636 bytes, where I use log10(n) (the log to base 10) as an approximation to the number of digits of n. This is only 143 MB, but I still get a stack overflow exception. Why does this happen?
using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger hugeFactorial = Calculations.Factorial(5000);
}
}
class Calculations
{
public static BigInteger Factorial(int n)
{
if (n == 1) return n;
else return n*Factorial(n - 1);
}
}