binomialCoefficient
Calculates the number of ways to choose k
items from n
items without repetition and without order.
- Use
Number.isNaN()
to check if any of the two values isNaN
. - Check if
k
is less than0
, greater than or equal ton
, equal to1
orn - 1
and return the appropriate result. - Check if
n - k
is less thank
and switch their values accordingly. - Loop from
2
throughk
and calculate the binomial coefficient. - Use
Math.round()
to account for rounding errors in the calculation.
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};