Skip to content

Instantly share code, notes, and snippets.

@AdamWhiteHat
Created December 22, 2020 12:48
Show Gist options
  • Save AdamWhiteHat/8fbbf7e57d4974f01faa6b933bf36e2e to your computer and use it in GitHub Desktop.
Save AdamWhiteHat/8fbbf7e57d4974f01faa6b933bf36e2e to your computer and use it in GitHub Desktop.
A fast factorial implementation using the divide and conquer method.
public static class FastFactorial
{
public static BigInteger Factorial(BigInteger n)
{
return MultiplyRange(2, n);
}
private static BigInteger MultiplyRange(BigInteger from, BigInteger to)
{
var diff = to - from;
if (diff == 1) { return from * to; }
if (diff == 0) { return from; }
BigInteger half = (from + to) / 2;
return BigInteger.Multiply(MultiplyRange(from, half), MultiplyRange(half + 1, to));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment