A binomial coefficient C(n, k) represents the number of ways to choose k objects from n objects without considering their order. It is also the coefficient of x^k in the expansion of (1 + x)^n.
The binomial coefficient is calculated using the formula:
C(n,k)=k!/(n−k)!n!​
For example, C(4, 2) = 6 and C(5, 2) = 10.
The following approach can be used to calculate the binomial coefficient in JavaScript.
Approach: Using an Iterative Function
The binomial coefficient can be calculated without directly computing factorials. This avoids unnecessary calculations and makes the implementation more efficient.
- Create a function that accepts n and k.
- Validate that both values are integers.
- Return 0 if k is less than 0 or greater than n.
- Return 1 when k is 0 or equal to n.
- Use the smaller value between k and n - k to reduce the number of iterations.
- Calculate the coefficient iteratively using the formula.
- Return the rounded result.
function binomialCoefficient(n, k) {
// Check whether n and k are integers
if (!Number.isInteger(n) || !Number.isInteger(k)) {
return NaN;
}
// Check for invalid values
if (k < 0 || k > n) {
return 0;
}
// Base cases
if (k === 0 || k === n) {
return 1;
}
// Use the smaller value of k and n - k
k = Math.min(k, n - k);
let result = 1;
// Calculate C(n, k)
for (let i = 1; i <= k; i++) {
result *= (n - i + 1) / i;
}
return Math.round(result);
}
console.log(binomialCoefficient(10, 2));
console.log(binomialCoefficient(5, 2));
console.log(binomialCoefficient(4, 2));
Output
45 10 6
Syntax:
binomialCoefficient(n, k);- n: The total number of objects.
- k: The number of objects to be selected.
- The function returns C(n, k).
Note: Number.isInteger() is used to ensure that n and k are integers. For very large values, JavaScript's Number type may lose integer precision; BigInt can be used when exact results beyond the safe integer range are required.
Time Complexity: O(min(k, n - k))
Auxiliary Space: O(1)