Skip to content

Instantly share code, notes, and snippets.

@rakeshta
Created May 22, 2025 06:46
Show Gist options
  • Save rakeshta/53c9d7a038382c0c6c00974dda9654d5 to your computer and use it in GitHub Desktop.
Save rakeshta/53c9d7a038382c0c6c00974dda9654d5 to your computer and use it in GitHub Desktop.
Computes the binomial coefficient of the given pair of integers
/**
* Computes the binomial coefficient of the given pair of integers. This can be used
* to compute the number of unique sets of `k` items that can be formed
* from a set of `n` items.
*
* An example usage is for counting the number of possible winning combinations in
* a combo multi formed with `n` legs where `k` legs should win.
*
* The original formula for this is:
* ```
* C(n, r) = n! / (r! * (n - r)!)
* ```
*
* This is an optimized implementation that takes advantage of the facts that both `n` and `r` are
* positive integers and that `n` is greater than `r`.
*
* @param n The number of items in the source set. Or the number of legs in the combo multi.
* @param r The number of items that target sets. Or the number of legs in the combo multi that should win.
* @returns The binomial coefficient. Or the number of possible winning combinations for the combo multi.
*
* @see https://en.wikipedia.org/wiki/Binomial_coefficient
* @see https://www.calculatorsoup.com/calculators/discretemathematics/combinations.php
* @see https://www.w3resource.com/javascript-exercises/javascript-math-exercise-20.php
*/
export function binomialCoefficient(n: number, k: number): number {
let coeff = 1;
for (let x = n - k + 1; x <= n; x++) {
coeff *= x;
}
for (let y = 1; y <= k; y++) {
coeff /= y;
}
return coeff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment