Compute nCr without overflow in JavaScript
Advanced · 4 min read
How many different five-card poker hands can you deal? How many ways can you choose 6 numbers from 49 on a lottery ticket? Questions like these are about combinations, and the answer is a count, so it must be a whole number. The formula in every textbook uses factorials, and in JavaScript that formula can hand you a count with a decimal point in it.
In this tutorial you will compute permutations P(n, r) and combinations C(n, k) without building a single factorial. You will check them against two famous numbers, 2598960 poker hands and 13983816 lottery tickets, watch the factorial formula fail, and then use BigInt for a 30-digit answer. You need to know for loops and arrow functions.
Permutations and combinations
- A permutation counts ordered picks. Choosing a gold, silver and bronze winner from 5 runners: 5 choices for gold, then 4 for silver, then 3 for bronze, so
P(5, 3) = 5 * 4 * 3 = 60. - A combination counts picks where order doesn't matter. Choosing 3 runners for a team from 5: each team of 3 can be ordered in 3 * 2 * 1 = 6 ways, so
C(5, 3) = 60 / 6 = 10.
The textbook formula is C(n, k) = n! / (k! * (n - k)!), where n! is the factorial, every number from 1 to n multiplied together.
Why factorials are a problem
Factorials grow very fast. 30! has 33 digits, far more than a JavaScript number can hold exactly. The answer C(30, 15) has only 9 digits. Building huge numbers just to divide them back down loses precision along the way.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
90 Permutations and combinations without losing the integer
hardCompute P(n, r) and C(n, k) without ever building a factorial. Check them against the two numbers everyone knows — 2598960 five-card hands and 13983816 six-from-49 lottery tickets — then show that the factorial route makes C(30, 15) a non-integer, and go to BigInt for C(100, 50).
Stuck? Three hints, smallest first
- 1.
P(n, r)isn * (n - 1) * ...forrterms. No division needed. - 2. For
C(n, k), multiply by one factor and divide by one factor in turn, so the running value stays an integer. - 3.
C(n, k)isC(n, n - k), so replacekwith the smaller of the two first.
Step 1: permutations with no division
const permutations = (n, r) => {
let result = 1;
for (let i = 0; i < r; i++) result *= n - i;
return result;
};
console.log(permutations(5, 3), permutations(30, 5)); // 60 17100720
Multiply n, n - 1, n - 2 and so on, r times. There is no factorial and no division, so nothing gets rounded.
Step 2: the factorial route, and where it fails
const factorial = (n) => {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
};
const combinationsByFactorial = (n, k) => factorial(n) / (factorial(k) * factorial(n - k));
console.log(combinationsByFactorial(5, 3)); // 10
console.log(combinationsByFactorial(30, 15)); // 155117519.99999997
For small numbers it works. For C(30, 15) it gives 155117519.99999997. You can't choose a team in 0.99999997 of a way. 30! was rounded when it was stored, and dividing can't bring back what was lost.
Step 3: multiply and divide in step
The trick is to never let the number grow bigger than it needs to. Multiply by one factor from the top, then divide by one from the bottom, over and over.
const combinations = (n, k) => {
const m = Math.min(k, n - k);
let result = 1;
for (let i = 1; i <= m; i++) result = (result * (n - m + i)) / i;
return result;
};
console.log(combinations(5, 3), combinations(30, 15)); // 10 155117520
Trace C(5, 2): after i = 1 the result is 4 / 1 = 4, and after i = 2 it is 4 * 5 / 2 = 10. After each round, the result is itself a smaller combination (C(4, 1), then C(5, 2)), so it is always a whole number and the division is always exact.
Step 4: why Math.min
Choosing 47 cards to keep from 52 is the same as choosing 5 to throw away. So C(n, k) equals C(n, n - k), and the smaller of the two means fewer rounds.
console.log(combinations(52, 5), combinations(52, 47) === combinations(52, 5)); // 2598960 true
console.log(combinations(49, 6)); // 13983816
2598960 poker hands and 13983816 lottery tickets, both exactly right.
Step 5: Pascal's triangle
Each row of Pascal's triangle lists C(n, 0) to C(n, n).
const add = (a, b) => a + b;
const pascalRow = (n) => Array.from({ length: n + 1 }, (unused, k) => combinations(n, k));
console.log(pascalRow(6), pascalRow(6).reduce(add, 0)); // [ 1, 6, 15, 20, 15, 6, 1 ] 64
Array.from({ length: n + 1 }, ...) builds an array by calling the function once for each position k. The row is the same read from either end, which is C(n, k) = C(n, n - k) again. It adds up to 2 ** 6 = 64.
Step 6: printed versus stored
console.log(combinations(60, 30)); // 118264581564861420
console.log(String(BigInt(combinations(60, 30)))); // 118264581564861424
This one is subtle. JavaScript prints 118264581564861420 but stores 118264581564861424. Above 2 ** 53, JavaScript prints the shortest digits that still point to the same stored value, and here those end in 0. BigInt(x) shows the real stored value, and it is the exact answer.
Step 7: when Number really is wrong
BigInt is a type for whole numbers of any size, written with n at the end. Use it for the factorial route and nothing is rounded.
const factorialBig = (n) => {
let result = 1n;
for (let i = 2n; i <= n; i++) result *= i;
return result;
};
const combinationsBig = (n, k) => factorialBig(n) / (factorialBig(k) * factorialBig(n - k));
console.log(String(BigInt(combinations(100, 50)))); // 100891344545564219663900999680
console.log(String(combinationsBig(100n, 50n))); // 100891344545564193334812497256
C(100, 50) has 30 digits, far beyond what a double can store exactly, so the Number version goes wrong from the 16th digit. The BigInt version keeps every digit. With BigInt the factorial formula is fine, because nothing is ever rounded.
The full solution
The answer panel has permutations, combinations, both factorial routes and pascalRow, and prints every count above, the C(30, 15) failure, the C(60, 30) printing puzzle and C(100, 50) both ways. Press Run to see the output.
const add = (a, b) => a + b;
const permutations = (n, r) => {
let result = 1;
for (let i = 0; i < r; i++) result *= n - i;
return result;
};
// Multiply then divide in step: the running value is a binomial coefficient at
// every stage, so it is always an integer and never grows past the answer.
const combinations = (n, k) => {
const m = Math.min(k, n - k);
let result = 1;
for (let i = 1; i <= m; i++) result = (result * (n - m + i)) / i;
return result;
};
const factorial = (n) => {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
};
const combinationsByFactorial = (n, k) => factorial(n) / (factorial(k) * factorial(n - k));
const factorialBig = (n) => {
let result = 1n;
for (let i = 2n; i <= n; i++) result *= i;
return result;
};
const combinationsBig = (n, k) => factorialBig(n) / (factorialBig(k) * factorialBig(n - k));
const pascalRow = (n) => Array.from({ length: n + 1 }, (unused, k) => combinations(n, k));
console.log('P(5, 3), P(30, 5) :', permutations(5, 3), permutations(30, 5));
console.log('C(5, 3), C(52, 5) :', combinations(5, 3), combinations(52, 5));
console.log('C(49, 6) :', combinations(49, 6));
console.log('C(30, 15) two ways :', combinationsByFactorial(30, 15), combinations(30, 15));
console.log('integer? :', Number.isInteger(combinationsByFactorial(30, 15)), Number.isInteger(combinations(30, 15)));
console.log('C(60, 30) printed :', combinations(60, 30), 'exact value', String(BigInt(combinations(60, 30))));
console.log('C(100, 50) double :', String(BigInt(combinations(100, 50))));
console.log('C(100, 50) BigInt :', String(combinationsBig(100n, 50n)));
console.log('Pascal row 6 :', pascalRow(6), 'sums to', pascalRow(6).reduce(add, 0));
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('P(5, 3) is 60 and P(30, 5) is 17100720, with no division anywhere', [permutations(5, 3), permutations(30, 5)], [60, 17100720]);
test('C(5, 3) is 10, and a five-card hand from 52 has 2598960 possibilities', [combinations(5, 3), combinations(52, 5)], [10, 2598960]);
test('a six-from-49 lottery ticket is one of 13983816', combinations(49, 6), 13983816);
test('the factorial route makes C(30, 15) a non-integer, which cannot be right', [combinationsByFactorial(30, 15), Number.isInteger(combinationsByFactorial(30, 15))], [155117519.99999997, false]);
test('multiplying and dividing in step keeps it exact', [combinations(30, 15), Number.isInteger(combinations(30, 15))], [155117520, true]);
test('C(n, k) equals C(n, n - k), and a Pascal row sums to 2 ** n', [combinations(52, 47) === combinations(52, 5), pascalRow(6), pascalRow(6).reduce(add, 0)], [true, [1, 6, 15, 20, 15, 6, 1], 64]);
test('C(60, 30) prints as ...420 but the double holds ...424, and that is exact', [combinations(60, 30), String(BigInt(combinations(60, 30))), String(combinationsBig(60n, 30n))], [118264581564861420, '118264581564861424', '118264581564861424']);
test('C(100, 50) is past exact, and the double is out by twenty-six thousand million', [BigInt(combinations(100, 50)) === combinationsBig(100n, 50n), String(BigInt(combinations(100, 50)))], [false, '100891344545564219663900999680']);
test('BigInt gets all thirty digits of C(100, 50)', [String(combinationsBig(100n, 50n)), String(combinationsBig(100n, 50n)).length], ['100891344545564193334812497256', 30]);
Never compute n! / (k! * (n - k)!) literally. Both factorials explode long before the answer does, and once they pass the exact range the division cannot undo the rounding — C(30, 15) comes back as 155117519.99999997, a count of things that is not a whole number. The in-step version multiplies by (n - m + i) and divides by i on each pass, and the running value is itself a binomial coefficient every time round, so it is always an integer and never exceeds the final answer.
Replacing k with Math.min(k, n - k) halves the work in the worst case and costs one line. It is free because C(n, k) === C(n, n - k), which is also the symmetry you can see in any row of Pascal's triangle.
C(60, 30) is the subtle one. JavaScript prints it as 118264581564861420, and the exact value is 118264581564861424 — but those are the same double. Above 2 ** 53 the printer emits the shortest decimal that round-trips, and the shortest one here ends in a zero. So an unsafe integer is not automatically a wrong one, and BigInt(x) is the way to ask what a double really holds. At C(100, 50) the double genuinely is wrong, from the eighteenth digit onwards, and only BigInt has the answer.
Common mistakes
- Using the factorial formula with Numbers. The factorials overflow long before the answer does. Multiply and divide in step.
- Dividing before multiplying in the loop.
result / i * (n - m + i)can leave a fraction partway through. Multiply first, then divide. - Thinking a printed number ending in 0 is rounded. Above 2 ** 53, use
BigInt(x)to see what is really stored.
Try it yourself
- How many ways can a class of 30 pick a president, a secretary and a treasurer? And how many ways can it pick a committee of 3?
- Print the first 8 rows of Pascal's triangle with
pascalRow. - Write
combinationsBigInStep(n, k)that uses the multiply-then-divide loop with BigInt values, and check it againstcombinationsBig(100n, 50n).