Combinations nCr and permutations nPr in JavaScript
Advanced · 4 min read
How many different five-card hands can you deal from a 52-card deck? The answer is a combination, written C(52, 5) or "52 choose 5": the number of ways to pick 5 items from 52 when order doesn't matter. If order does matter, like first, second and third place in a race, you want a permutation, P(n, k).
These two counts show up in probability, in lotteries, in testing (how many pairs of settings?) and in Pascal's triangle. The textbook formulas use factorials, and in JavaScript those break much sooner than you would expect. In this tutorial you will see the factorial formula fail, build a version that multiplies and divides as it goes, and then build a row of Pascal's triangle two ways and find where they disagree. You need to know loops and what a factorial is.
The formulas
The number of ordered picks is P(n, k) = n × (n - 1) × ... with k numbers multiplied. For 3 places from 10 runners that is 10 × 9 × 8 = 720.
Each unordered group of k items can be ordered in k! ways, so C(n, k) is P(n, k) divided by k!. Written with factorials:
C(n, k) = n! / (k! × (n - k)!)
That formula is correct. The problem is that n! gets huge long before the answer does.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
55 Combinations, permutations and a row of Pascal
hardCompute nCr and nPr without building a factorial first. Show the factorial route failing on C(200, 100), then produce a row of Pascal's triangle two ways and find where they disagree.
Stuck? Three hints, smallest first
- 1. Multiply and divide alternately:
r = r * (n - k + i) / ikeeps every intermediate as a binomial coefficient. - 2.
C(n, k) === C(n, n - k), so replacekwith the smaller of the two first. - 3. A row can be built from
C(n, k)for eachk, or from the row above by adding neighbours.
Step 1: the factorial route
const factorial = (n) => {
let p = 1;
for (let k = 2; k <= n; k++) p *= k;
return p;
};
const chooseByFactorials = (n, k) => factorial(n) / (factorial(k) * factorial(n - k));
console.log(chooseByFactorials(5, 2)); // 10
console.log(chooseByFactorials(52, 5)); // 2598960
Both are right. There are 2,598,960 five-card hands.
Step 2: where it breaks
console.log(chooseByFactorials(30, 15)); // 155117519.99999997
console.log(chooseByFactorials(200, 100)); // NaN
C(30, 15) is 155117520, but the formula gives a value with a decimal tail. 30! is about 2.65e32, far too big to store exactly, so rounding creeps in before the division.
C(200, 100) is worse. The true answer is about 9.05e58, comfortably inside the range of a JavaScript number. But 200! is Infinity, and Infinity / Infinity is NaN. The answer fits; the middle of the calculation doesn't.
Step 3: multiply and divide as you go
Instead of building three huge factorials, build the answer one factor at a time. After step i, the running result is itself a smaller combination, so it is always a whole number:
let r = 1;
const n = 5;
const k = 2;
for (let i = 1; i <= k; i++) {
r = (r * (n - k + i)) / i;
console.log(i, r);
}
// prints 1 4, then 2 10
First 1 × 4 / 1 = 4, then 4 × 5 / 2 = 10. The division always comes out even, and the numbers never get bigger than they need to.
Step 4: the choose function
function choose(n, k) {
if (k < 0 || k > n) return 0;
k = Math.min(k, n - k);
let result = 1;
for (let i = 1; i <= k; i++) result = (result * (n - k + i)) / i;
return result;
}
console.log(choose(5, 2)); // 10
console.log(choose(30, 15)); // 155117520
console.log(choose(200, 100)); // 9.054851465610333e+58
console.log(choose(5, 6)); // 0
Three details. Picking more items than you have is impossible, so that returns 0. Choosing k items is the same as choosing which n - k to leave out, so C(9, 2) equals C(9, 7). Math.min(k, n - k) uses the smaller one, which means fewer loop passes and smaller numbers along the way. And C(30, 15) is now exact.
Step 5: permutations
const permute = (n, k) => {
if (k < 0 || k > n) return 0;
let result = 1;
for (let i = 0; i < k; i++) result *= n - i;
return result;
};
console.log(permute(52, 5)); // 311875200
console.log(choose(52, 5) * factorial(5)); // 311875200
P(52, 5) multiplies 52 × 51 × 50 × 49 × 48. It equals C(52, 5) times 5!, because each hand can be ordered in 5! = 120 ways.
Step 6: a row of Pascal's triangle, by product
Row n of Pascal's triangle is C(n, 0), C(n, 1), ... up to C(n, n). Each entry can be worked out from the one before it:
function rowByProduct(n) {
const row = [1];
for (let k = 0; k < n; k++) row.push((row[k] * (n - k)) / (k + 1));
return row;
}
console.log(rowByProduct(5)); // [ 1, 5, 10, 10, 5, 1 ]
console.log(choose(56, 28)); // 7648690600760440
console.log(rowByProduct(56)[28]); // 7648690600760441
Row 5 is right. But at row 56, the middle entry is one too high. The true value 7648690600760440 is still a safe integer. The problem is row[k] * (n - k): the multiplication happens first, the intermediate goes past MAX_SAFE_INTEGER, and it gets rounded before the division. choose(56, 28) gives the exact value.
Step 7: a row by addition
Pascal's own rule is that each entry is the sum of the two above it. That uses only addition, so nothing is rounded until the entries themselves get too big:
function rowByAddition(n) {
let row = [1];
for (let i = 0; i < n; i++) {
const next = [1];
for (let j = 0; j < row.length - 1; j++) next.push(row[j] + row[j + 1]);
next.push(1);
row = next;
}
return row;
}
console.log(rowByAddition(5)); // [ 1, 5, 10, 10, 5, 1 ]
console.log(rowByAddition(56)[28]); // 7648690600760440
Exact. Building 56 rows is more work than one row by product, but every number along the way is a sum of smaller exact numbers.
The full solution
The answer panel has factorial, both choose versions, permute and both row builders, then prints C(5, 2), the card counts, C(200, 100) both ways, row 5, and the row-56 entry from choose and from both row builders. Press Run to see the output.
const factorial = (n) => {
let p = 1;
for (let k = 2; k <= n; k++) p *= k;
return p;
};
const chooseByFactorials = (n, k) => factorial(n) / (factorial(k) * factorial(n - k));
// Alternating multiply and divide: every intermediate is itself a C(m, i).
function choose(n, k) {
if (k < 0 || k > n) return 0;
k = Math.min(k, n - k);
let result = 1;
for (let i = 1; i <= k; i++) result = (result * (n - k + i)) / i;
return result;
}
const permute = (n, k) => {
if (k < 0 || k > n) return 0;
let result = 1;
for (let i = 0; i < k; i++) result *= n - i;
return result;
};
// A row by running product, which drifts, ...
function rowByProduct(n) {
const row = [1];
for (let k = 0; k < n; k++) row.push((row[k] * (n - k)) / (k + 1));
return row;
}
// ... and a row by addition, which does not.
function rowByAddition(n) {
let row = [1];
for (let i = 0; i < n; i++) {
const next = [1];
for (let j = 0; j < row.length - 1; j++) next.push(row[j] + row[j + 1]);
next.push(1);
row = next;
}
return row;
}
console.log('C(5, 2) :', choose(5, 2));
console.log('C(52, 5) :', choose(52, 5), 'P(52, 5):', permute(52, 5));
console.log('C(200, 100) via factorials:', chooseByFactorials(200, 100));
console.log('the same, multiplied out :', choose(200, 100));
console.log('row 5 :', rowByProduct(5));
console.log('C(56, 28) :', choose(56, 28));
console.log('row 56 at k=28 :', rowByProduct(56)[28], '<- one too many');
console.log('by addition :', rowByAddition(56)[28]);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('C(5, 2) is 10, and the edges are 1', [choose(5, 2), choose(5, 0), choose(5, 5), choose(5, 6)], [10, 1, 1, 0]);
test('there are 2598960 five-card hands in a 52-card deck', choose(52, 5), 2598960);
test('ordered, that is 311875200, which is C times 5!', [permute(52, 5), choose(52, 5) * factorial(5)], [311875200, 311875200]);
test('C(n, k) equals C(n, n - k)', [0, 1, 2, 3].map((k) => choose(9, k) === choose(9, 9 - k)), [true, true, true, true]);
test('the factorial route gives NaN for C(200, 100), since 200! is Infinity', [Number.isNaN(chooseByFactorials(200, 100)), factorial(200) === Infinity], [true, true]);
test('multiplying and dividing alternately survives it', choose(200, 100), 9.054851465610333e58);
test('C(56, 28) is exact and still a safe integer', [choose(56, 28), Number.isSafeInteger(choose(56, 28))], [7648690600760440, true]);
test('but the running-product row gets that entry one too high', rowByProduct(56)[28], 7648690600760441);
test('while building the row by addition keeps it exact', [rowByProduct(5), rowByAddition(56)[28]], [[1, 5, 10, 10, 5, 1], 7648690600760440]);
C(200, 100) is about 9.05e58, comfortably inside a double's range, and the factorial route still returns NaN — because 200! is Infinity and Infinity / Infinity is undefined. The multiplicative loop never builds a value larger than the answer, so it returns something usable. Reducing k to min(k, n - k) first halves the iterations and lowers every intermediate, for free, by symmetry.
The two row builders disagree at row 56, and the reason is the order of operations rather than the size of the answer. C(56, 28) is 7648690600760440, still a safe integer; the running product row[k] * (n - k) / (k + 1) passes through intermediates near 2 ** 53 where a division rounds, and the error survives to the end as an off-by-one. Pascal's own rule — each entry is the sum of the two above it — uses nothing but integer addition, so it stays exact for as long as the entries themselves fit.
Common mistakes
- Computing three factorials and dividing. 200! is
Infinity, so C(200, 100) comes outNaNeven though the answer fits. - Forgetting the
k > ncase. There are 0 ways to pick 6 items from 5. Return 0 instead of looping. - Assuming a safe answer means a safe calculation. C(56, 28) is safe, but the running-product row passes through a larger intermediate and comes out one too high.
Try it yourself
- A lottery draws 6 numbers from 49. Use
chooseto find how many tickets cover every possible draw. - Ten runners race. Use
permuteto count the possible gold, silver and bronze results. - Find the first row n where
rowByProduct(n)androwByAddition(n)disagree anywhere.