I need to calculate a very large factorial, however it must be exact. I can't use an approximation.
I want to get 1,000,000,000!, but it's pretty slow. So far I have improved performance a bit, but its still not enough. Here is what I have:
BigInteger Factor100 = BigInteger.One;
BigInteger Factor10000 = BigInteger.One;
Status = "Factorising";
for (i++; i <= StartN; i++)
{
if (Worker.CancellationPending)
{
e.Cancel = true;
break;
}
if (i % 10000 == 0)
{
Factor100 = Factor100 * i;
Factor10000 = Factor10000 * Factor100;
iFactorial = iFactorial * Factor10000;
Factor100 = BigInteger.One;
Factor10000 = BigInteger.One;
}
else if (i % 100 == 0)
{
Factor100 = Factor100 * i;
Factor10000 = Factor10000 * Factor100;
Factor100 = BigInteger.One;
}
else
{
Factor100 = Factor100 * i;
}
//iFactorial = i * iFactorial;
if (i % Updates == 0)
{
Worker.ReportProgress(50, new Tuple<string, BigInteger>("Factorialising", i));
using (StreamWriter DropWriter = File.CreateText(@FileLocation + "FactorialDropCatcher.dat"))
{
DropWriter.WriteLine("N: " + i);
DropWriter.WriteLine("N!: " + iFactorial);
}
}
}
So, I tried to stay away from calculating the insanely large numbers until it became necessary, keeping the running Factorial number updated only once every 10,000.
How could I calculate this faster?