First, I note that you are trying to calculate a binomial coefficient, so call it that.
Here are a few calculation methods. If you use BigInteger, you do not need to worry about overflow:
First method: use factorial:
static BigInteger Factorial(BigInteger n) { BigInteger f = 1; for (BigInteger i = 2; i <= n; ++i) f = f * i; return f; } static BigInteger BinomialCoefficient(BigInteger n, BigInteger k) { return Factorial(n) / (Factorial(nk) * Factorial(k)); }
Method two: use recursion:
static BigInteger BinomialCoefficient(BigInteger n, BigInteger k) { if (n == 0) return 1; if (k == 0) return 0; return BinomialCoefficient(n-1, k-1) + BinomialCoefficient(n-1, k) }
This method, however, is not fast unless you memoize the result.
The third method: be smarter in minimizing the number of multiplications and divide earlier. This reduces the number of numbers:
static BigInteger BinomialCoefficient(BigInteger n, BigInteger k) {
So, for example, if you calculated (6 C 3) instead of calculating (6 x 5 x 4 x 3 x 2 x 1) / ((3 x 2 x 1) x (3 x 2 x 1)), you calculate (( (4/1) * 5) / 2) * 6) / 3, which allows, if possible, small numbers.
source share