Emmanuel Akinfulubi

JavaScriptMath

Calculate 100 factorial with BigInt in JavaScript

Intermediate · 4 min read

100 factorial, written 100!, means 1 * 2 * 3 * ... * 100. The answer has 158 digits. An ordinary JavaScript number can only hold about 16 of them, so it gives you a rounded version and quietly guesses the rest. With BigInt you get every digit, exactly.

In this tutorial you will compute 100! exactly, count its digits and trailing zeros, and add up its digits. Then you will use the same tool on Fibonacci numbers and on "100 choose 50", a number from probability that is easy to compute badly. You will finish with the four places where BigInt refuses to mix with ordinary numbers, so you know them before they surprise you. You need to know for loops and strings.

What BigInt is

A BigInt is a whole number of any size. You write one by putting n after the digits, or by passing a whole number to BigInt():

JavaScript

console.log(2n ** 100n);            // 1267650600228229401496703205376n
console.log(BigInt(10) === 10n);   // true

node prints a BigInt with its n on the end. String(value) gives just the digits, which is what you want for display.

The one rule to remember

BigInt and Number are separate types, and JavaScript won't convert between them for you in arithmetic. Both sides of +, -, *, / and ** need to be BigInt. Comparisons are the exception: 5n <= 10 is true.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

108 A hundred factorial, exactly

fair

Compute 100! exactly with BigInt and report its digit count, its trailing zeros and its digit sum. Then find the first Fibonacci number a double gets wrong, compute the 200th exactly, and work out C(100, 50) without ever forming a factorial you cannot hold. Finish with the four ways BigInt refuses to co-operate with Number.

Stuck? Three hints, smallest first
  1. 1. A BigInt literal ends in n, and the loop counter has to be a BigInt too, because mixing the two types throws.
  2. 2. The trailing zeros of n! count the factors of 10, so count the factors of 5: floor(100/5) + floor(100/25).
  3. 3. For a binomial coefficient, multiply and divide alternately — the running value stays whole at every step, so no giant intermediate is needed.

Step 1: a factorial loop in BigInt

Step 1

function factorial(n) {
  let product = 1n;
  for (let k = 2n; k <= BigInt(n); k++) product *= k;
  return product;
}
console.log(String(factorial(10))); // 3628800
const text = String(factorial(100));
console.log(text.length, text.slice(0, 10)); // 158 9332621544

Both product and the counter k are BigInts, so product *= k is BigInt times BigInt. k++ works on BigInts too. BigInt(n) lets you call factorial(100) with a plain number.

Step 2: the wrong turn, plain numbers

Step 2

function factorialDouble(n) {
  let product = 1;
  for (let k = 2; k <= n; k++) product *= k;
  return product;
}
console.log(factorialDouble(100));    // 9.33262154439441e+157
console.log(Number(factorial(100))); // 9.332621544394415e+157

The loop finishes without any error, but each of its 99 multiplications rounds. Compare the two lines. The exact value, turned into a number once at the end, reads 9.332621544394415. The plain loop reads 9.33262154439441, so its error has already reached the 16th digit. The other 142 digits aren't stored by either one.

Step 3: trailing zeros

Step 3

let trailingZeros = 0;
while (text[text.length - 1 - trailingZeros] === '0') trailingZeros++;
const legendre = Math.floor(100 / 5) + Math.floor(100 / 25);
console.log(trailingZeros, legendre); // 24 24

The loop counts zeros from the end of the string. You can also predict them without the number at all. Each trailing zero is a factor of 10, which is 2 * 5. There are plenty of 2s, so count the 5s: twenty multiples of 5 up to 100, and four of those (25, 50, 75, 100) give a second 5. That is 24.

Step 4: add up the digits

Step 4

const digitSum = [...text].reduce((a, d) => a + Number(d), 0);
console.log(digitSum); // 648

[...text] splits the string into single characters, and Number(d) turns each back into a digit.

Step 5: where Fibonacci goes wrong

Step 5

function fib(n) {
  let a = 0n;
  let b = 1n;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
}
function fibDouble(n) {
  let a = 0;
  let b = 1;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
}
let firstWrong = 0;
for (let i = 1; i <= 100 && firstWrong === 0; i++) {
  if (BigInt(fibDouble(i)) !== fib(i)) firstWrong = i;
}
console.log(firstWrong, String(fib(79)), fibDouble(79)); // 79 14472334024676221 14472334024676220

The same loop, written twice. The search compares them one index at a time and stops at the first difference. At index 79 the plain version is off by exactly 1.

Step 6: 100 choose 50 without giant numbers

"100 choose 50", written C(100, 50), is the number of ways to pick 50 things from 100. The textbook formula is 100! / (50! * 50!), which needs huge factorials. There is a gentler way: multiply and divide one step at a time.

Step 6

function choose(n, k) {
  let result = 1n;
  for (let i = 1n; i <= BigInt(k); i++) result = (result * (BigInt(n) - BigInt(k) + i)) / i;
  return result;
}
console.log(String(choose(5, 2)), String(choose(100, 50))); // 10 100891344545564193334812497256

After each step, result is itself a smaller "choose" number, so it is always a whole number. That matters because BigInt division throws away any remainder. The running value never gets bigger than the answer.

Step 7: where BigInt refuses

Step 7

const refusals = [];
try { refusals.push(1n + 1); } catch (e) { refusals.push(e.constructor.name); }
try { refusals.push(JSON.stringify({ total: 1n })); } catch (e) { refusals.push(e.constructor.name); }
try { refusals.push(Math.sqrt(4n)); } catch (e) { refusals.push(e.constructor.name); }
try { refusals.push(BigInt(1.5)); } catch (e) { refusals.push(e.constructor.name); }
console.log(refusals); // [ 'TypeError', 'TypeError', 'TypeError', 'RangeError' ]

Each try catches the error and records its type. Mixing BigInt with a Number throws. JSON.stringify can't save a BigInt. The Math functions only take Numbers. And BigInt(1.5) throws a RangeError, because 1.5 isn't a whole number.

Step 8: division and late conversion

Step 8

console.log(String(7n / 2n), String(-7n / 2n));                // 3 -3
console.log(String(BigInt(Number.MAX_SAFE_INTEGER + 2)));      // 9007199254740992

BigInt division drops the fraction and rounds toward zero. The second line asks for 9007199254740993 and gets ...992, because the plain number was already rounded before BigInt saw it. Convert to BigInt first, then do the math.

The full solution

The answer panel has factorial, both Fibonacci loops and choose, and prints every result above, including F(200), all 42 digits of it. Press Run to see the output.

The answer

function factorial(n) {
  let product = 1n;
  for (let k = 2n; k <= BigInt(n); k++) product *= k;
  return product;
}

function factorialDouble(n) {
  let product = 1;
  for (let k = 2; k <= n; k++) product *= k;
  return product;
}

function fib(n) {
  let a = 0n;
  let b = 1n;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
}

function fibDouble(n) {
  let a = 0;
  let b = 1;
  for (let i = 0; i < n; i++) {
    const next = a + b;
    a = b;
    b = next;
  }
  return a;
}

// Multiply then divide, alternately: the running value is a binomial coefficient
// at every step, so it is always whole and never larger than the answer.
function choose(n, k) {
  let result = 1n;
  for (let i = 1n; i <= BigInt(k); i++) result = (result * (BigInt(n) - BigInt(k) + i)) / i;
  return result;
}

const f100 = factorial(100);
const text = String(f100);
let trailingZeros = 0;
while (text[text.length - 1 - trailingZeros] === '0') trailingZeros++;
const legendre = Math.floor(100 / 5) + Math.floor(100 / 25);
const digitSum = [...text].reduce((a, d) => a + Number(d), 0);

// The first index where the double version stops telling the truth.
let firstWrong = 0;
for (let i = 1; i <= 100 && firstWrong === 0; i++) {
  if (BigInt(fibDouble(i)) !== fib(i)) firstWrong = i;
}

// The four refusals, caught so the panel survives them.
const refusals = [];
try { refusals.push(1n + 1); } catch (e) { refusals.push(e.constructor.name); }
try { refusals.push(JSON.stringify({ total: 1n })); } catch (e) { refusals.push(e.constructor.name); }
try { refusals.push(Math.sqrt(4n)); } catch (e) { refusals.push(e.constructor.name); }
try { refusals.push(BigInt(1.5)); } catch (e) { refusals.push(e.constructor.name); }

console.log('100!            :', text);
console.log('digits          :', text.length, 'trailing zeros', trailingZeros, 'digit sum', digitSum);
console.log('as a double     :', Number(f100), 'against the double loop', factorialDouble(100));
console.log('first wrong fib :', firstWrong, String(fib(firstWrong)), fibDouble(firstWrong));
console.log('fib 200         :', String(fib(200)));
console.log('C(100, 50)      :', String(choose(100, 50)), 'as a double', Number(choose(100, 50)));
console.log('refusals        :', refusals);
console.log('7n / 2n         :', String(7n / 2n), 'and -7n / 2n is', String(-7n / 2n));
console.log('lost before conversion:', String(BigInt(Number.MAX_SAFE_INTEGER + 2)));

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.

9 checks

test('100! is 158 digits long and starts 9332621544', [text.length, text.slice(0, 10)], [158, '9332621544']);
test('it ends in 24 zeros, which is exactly how many factors of 5 are in 1..100', [trailingZeros, legendre], [24, 24]);
test('and its digits add up to 648', digitSum, 648);
test('turned into a double it is 9.332621544394415e157, where a double loop gives 9.33262154439441e157', [Number(f100), factorialDouble(100)], [9.332621544394415e157, 9.33262154439441e157]);
test('the 79th Fibonacci number is the first a double gets wrong, by exactly 1', [firstWrong, String(fib(79)), fibDouble(79)], [79, '14472334024676221', 14472334024676220]);
test('the 200th has 42 digits and no double can hold it', [String(fib(200)), String(fib(200)).length], ['280571172992510140037611932413038677189525', 42]);
test('C(100, 50) is exact without a single overflow, and its double is not', [String(choose(100, 50)), Number(choose(100, 50))], ['100891344545564193334812497256', 1.008913445455642e29]);
test('mixing, serialising, rooting and fractional conversion all throw', refusals, ['TypeError', 'TypeError', 'TypeError', 'RangeError']);
test('BigInt division truncates towards zero, and 1n == 1 while 1n === 1 is false', [String(7n / 2n), String(-7n / 2n), 1n == 1, 1n === 1], ['3', '-3', true, false]);

Exercise 54 found the three places doubles give up on factorials: 18! is the last safe integer, 22! the last exactly representable, 170! the last finite one. BigInt has none of those ceilings. 100! is 158 digits, ends in 24 zeros — one per factor of 5 in 1..100, which Legendre's count gives as 20 + 4 without looking at the number at all — and its digits add to 648. The double loop gets the leading digits and then diverges: 9.33262154439441e157 against 9.332621544394415e157.

Fibonacci puts the boundary at index 79, and note what the failure looks like: 14472334024676220 instead of 14472334024676221. Off by one, no warning, and every later term inherits it. C(100, 50) is the other half of the lesson — the naive formula needs 100! and 50!, but multiplying and dividing alternately keeps the running value whole and never bigger than the answer, so it works in doubles right up to the point where the answer stops fitting.

The cost is that BigInt is a separate numeric type and will not quietly become a Number. 1n + 1 throws a TypeError, JSON.stringify throws on a BigInt anywhere in the object, every Math function throws, and BigInt(1.5) throws a RangeError. Division truncates towards zero rather than producing a fraction. And BigInt(Number.MAX_SAFE_INTEGER + 2) is 9007199254740992: converting late cannot recover precision the double already lost, so convert at the boundary, count in BigInt, and format with String.

Common mistakes

  • Using a plain-number loop counter. product *= k with k = 2 throws a TypeError when product is 1n.
  • Converting too late. BigInt(bigNumber) can't restore digits a plain number already lost.
  • Saving a BigInt with JSON. Turn it into a string first, with String(value).

Try it yourself

  1. Find the smallest n where n! has more than 1000 digits.
  2. Count the trailing zeros of 1000! with the factors-of-5 rule (remember 125 and 625), and check it against the string.
  3. Use choose to work out C(52, 5), the number of five-card poker hands.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.