Largest exact factorial in JavaScript
Advanced · 4 min read
The factorial of a number n, written n!, is every whole number from 1 to n multiplied together. 5! is 1 × 2 × 3 × 4 × 5, which is 120. Factorials count arrangements: 5! is the number of ways to line up five people. They grow extremely fast, which makes them a good way to find the limits of JavaScript numbers.
In this tutorial you will write factorial(n) with a loop, and a BigInt version to check it against. Then you will find three different limits: the last factorial that is a "safe" integer, the last one that is still exactly right, and the last one that isn't Infinity. They are not the same number, and mixing them up is a common mistake. You need to know loops and what Number.MAX_SAFE_INTEGER is.
Safe, exact and finite
A JavaScript number can hold every whole number exactly up to Number.MAX_SAFE_INTEGER, which is 9007199254740991, about 9 million billion. That is the safe range: inside it, no two neighboring whole numbers share the same stored value.
Above that range, only some whole numbers can be stored. Between 2 to the 53rd and 2 to the 54th, only even ones. Further up, only multiples of 4, then 8, and so on. A big number can still be stored exactly if it happens to be one of those.
Numbers stay finite up to about 1.8e308. Past that, a result becomes Infinity.
BigInt, for exact answers
A BigInt is a whole number with no size limit. You write one with an n on the end, like 5n. BigInts can't be mixed with ordinary numbers in arithmetic, so a BigInt loop uses BigInts throughout.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
54 Factorial, and where it stops being exact
hardCompute n! iteratively. Then find the largest factorial that is a safe integer, the largest that is exactly representable at all, and the smallest that overflows to Infinity.
Stuck? Three hints, smallest first
- 1. A product of every integer up to
n, starting from 1, so that0!is 1. - 2. "Safe" and "exact" are different: past
2 ** 53only some integers are representable, and a factorial has many factors of 2. - 3. A
BigIntversion alongside gives you something to compare against.
Step 1: the loop
function factorial(n) {
let product = 1;
for (let k = 2; k <= n; k++) product *= k;
return product;
}
console.log([0, 1, 2, 3, 4, 5].map(factorial)); // [ 1, 1, 2, 6, 24, 120 ]
console.log(factorial(10)); // 3628800
product starts at 1, not 0. Starting at 0 would make every answer 0. Starting at 1 also gives the right answers for 0! and 1!: the loop doesn't run at all, and both are defined as 1.
Step 2: the exact version
function factorialExact(n) {
let product = 1n;
for (let k = 2n; k <= BigInt(n); k++) product *= k;
return product;
}
console.log(factorialExact(25).toString()); // 15511210043330985984000000
Same loop, with 1n and 2n instead of 1 and 2. BigInt(n) converts the limit so the comparison mixes no types. This version is always right, so we can use it as the referee.
Step 3: the last safe factorial
let lastSafe = 0;
while (Number.isSafeInteger(factorial(lastSafe + 1))) lastSafe++;
console.log(lastSafe, factorial(lastSafe)); // 18 6402373705728000
The loop keeps going while the next factorial is still safe. It stops at 18. 19! is 121645100408832000, which is past MAX_SAFE_INTEGER.
Step 4: past safe, but still exact
Is 19! wrong, then? Compare it with the BigInt version:
console.log(factorial(19)); // 121645100408832000
console.log(factorialExact(19).toString()); // 121645100408832000
They match. 19! is outside the safe range but still exact. The reason: a factorial is a product of many numbers, and lots of them are even. 19! contains 2 multiplied in 16 times. Strip those out and what is left is small:
console.log(factorial(19) / 2 ** 16); // 1856156927625
1856156927625 easily fits in the safe range, and multiplying by a power of two is exact for a computer, so 19! lands on a number JavaScript can store exactly.
Step 5: the last exact factorial
Now test each factorial against the BigInt referee:
const isExact = (n) => Number.isInteger(factorial(n)) && BigInt(factorial(n)) === factorialExact(n);
let lastExact = 0;
while (isExact(lastExact + 1)) lastExact++;
console.log(lastExact); // 22
console.log(Number(BigInt(factorial(23)) - factorialExact(23))); // 1572864
22! is the last exact one. 23! comes back 1,572,864 too large. There is no error and no NaN: just a wrong number that looks perfectly reasonable. Any calculation that divides factorials, like counting combinations, inherits that error.
Step 6: the last finite factorial
let lastFinite = 0;
while (Number.isFinite(factorial(lastFinite + 1))) lastFinite++;
console.log(lastFinite, factorial(lastFinite)); // 170 7.257415615307994e+306
console.log(factorial(171)); // Infinity
console.log(factorial(171) / factorial(171)); // NaN
170! is about 7.26 times 10 to the 306th, close to the top of the range. 171! is Infinity. Divide Infinity by Infinity and you get NaN. That is still a wrong answer, but at least it is one you will notice.
So the three limits are 18 (safe), 22 (exact) and 170 (finite). For exact factorials of any size, use the BigInt version.
The full solution
The answer panel has factorial, factorialExact and isExact, finds all three limits with while loops, and prints 0! to 5!, 10!, the last safe and last exact values, 23! against its exact value, 170! and 171!. Press Run to see the output.
function factorial(n) {
let product = 1;
for (let k = 2; k <= n; k++) product *= k;
return product;
}
function factorialExact(n) {
let product = 1n;
for (let k = 2n; k <= BigInt(n); k++) product *= k;
return product;
}
const isExact = (n) => Number.isInteger(factorial(n)) && BigInt(factorial(n)) === factorialExact(n);
let lastSafe = 0;
while (Number.isSafeInteger(factorial(lastSafe + 1))) lastSafe++;
let lastExact = 0;
while (isExact(lastExact + 1)) lastExact++;
let lastFinite = 0;
while (Number.isFinite(factorial(lastFinite + 1))) lastFinite++;
console.log('0! to 5! :', [0, 1, 2, 3, 4, 5].map(factorial));
console.log('10! :', factorial(10));
console.log('last safe :', lastSafe, factorial(lastSafe));
console.log('last exact :', lastExact, factorial(lastExact));
console.log('23! :', factorial(23), 'against', factorialExact(23).toString());
console.log('last finite :', lastFinite, factorial(lastFinite));
console.log('171! :', factorial(171));
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('0! and 1! are both 1, and 5! is 120', [factorial(0), factorial(1), factorial(5)], [1, 1, 120]);
test('10! is 3628800, and matches a reduce over 1..10', [factorial(10), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce((a, b) => a * b, 1)], [3628800, 3628800]);
test('18! is the last factorial that is a safe integer', [lastSafe, factorial(18)], [18, 6402373705728000]);
test('19! is past MAX_SAFE_INTEGER yet still exactly representable', [Number.isSafeInteger(factorial(19)), isExact(19)], [false, true]);
test('because a factorial carries plenty of factors of 2', factorial(19) / 2 ** 16 === 1856156927625, true);
test('22! is the last one that is exact', [lastExact, isExact(22), isExact(23)], [22, true, false]);
test('23! comes back 1572864 too large', Number(BigInt(factorial(23)) - factorialExact(23)), 1572864);
test('170! is the last finite one, at about 7.26e306', [lastFinite, factorial(170)], [170, 7.257415615307994e306]);
test('171! overflows to Infinity, and ratios of it are NaN', [factorial(171) === Infinity, Number.isNaN(factorial(171) / factorial(171))], [true, true]);
Three different limits, and confusing them is the trap. Safe stops at 18!, where the value passes Number.MAX_SAFE_INTEGER and consecutive integers stop being distinguishable in general. Exact goes further, to 22!, because a factorial is divisible by a large power of two — 19! is 2 ** 16 times an odd number small enough to hold, so it lands precisely on a representable double. Finite reaches 170!, and 171! is Infinity.
23! is the interesting failure: no exception, no NaN, just an answer 1,572,864 too large. Any code that divides factorials — the naive binomial coefficient in exercise 55 is the obvious one — inherits that error and often amplifies it, and past 170 it inherits Infinity / Infinity instead, which at least announces itself as NaN. Factorials of any size belong in BigInt.
Common mistakes
- Starting the product at 0. Every factorial becomes 0. Start at 1.
- Treating "not safe" as "wrong". 19!, 20!, 21! and 22! are past the safe range and still exact. 23! is the first wrong one.
- Mixing BigInt and number.
1n * 2throws a TypeError. Keep the whole BigInt loop in BigInt.
Try it yourself
- Write
factorialRecursive(n)using recursion and check it matchesfactorialfrom 0 to 20. - Print
factorialExact(30).toString()and count its trailing zeros. - Find how many times 2 divides 22!. (Hint: keep dividing the BigInt by
2nwhile the remainder is0n.)