Created
December 22, 2020 12:48
-
-
Save AdamWhiteHat/8fbbf7e57d4974f01faa6b933bf36e2e to your computer and use it in GitHub Desktop.
A fast factorial implementation using the divide and conquer method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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