Implementation
double binomialCoefficient(double nr, double kr) {
int n = nr.floor();
int k = kr.floor();
if (n != nr || k != kr || n < 0 || k < 0 || k > n) {
throw CalculatorError(0);
}
k = min(k, n - k);
if (k > 200) {
// Enough to overflow the 15C
return double.infinity;
} else if (k == 1) {
return nr;
} else if (n > 10000) {
if (k > 36) {
// Enough to overflow the 15C
return double.infinity;
}
final kd = k.toDouble();
return permutations(nr, kd, initial: 1.0 / factorial(kd));
}
final c = Float64List(k + 1);
c[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = min(i, k); j > 0; j--) {
c[j] += c[j - 1];
if (c[j] == double.infinity) {
return c[j];
}
}
}
return c[k];
}