Find the factorial of a number

Factorial n! is the product of all integers from 1 to n (with 0! = 1); compute it iteratively in O(n) time, validate the input, and use BigInt because results exceed Number's safe range after 18! and overflow to Infinity after 170!.

Approaches

  • Iterative loop (best default): multiply an accumulator from 2 to n. O(n) time, O(1) space, no recursion limits.
  • Recursive: n * factorial(n - 1) with base case n <= 1. Clear, but uses O(n) stack and can overflow for very large n.
  • Memoised / table: useful when you need many factorials (for combinations nCr = n! / (r! (n-r)!)).
  • reduce over a range: concise, but builds an array first.

Input validation

Factorial is defined for non-negative integers. Reject negatives, fractions, NaN and non-numbers with a clear error. (The gamma function extends it to real numbers, but that is out of scope.)

Precision

  • Number is exact only up to 2^53 - 1; 18! is the largest factorial that fits exactly (19! loses precision).
  • 171! exceeds Number.MAX_VALUE and becomes Infinity.
  • BigInt keeps every digit: factorial(50n) is exact.

Follow-ups

  • Count trailing zeros of n! without computing it: count factors of 5 (n/5 + n/25 + ...).
  • Compute n! mod m for large n to stay within limits.

Code example

js
1function factorial(n) {
2 if (!Number.isInteger(n) || n < 0) throw new RangeError("n must be a non-negative integer");
3 let result = 1n;
4 for (let i = 2n; i <= BigInt(n); i++) result *= i;
5 return result;
6}
7
8const factorialRecursive = (n) => (n <= 1 ? 1 : n * factorialRecursive(n - 1)); // fine for small n
9
10console.log(factorial(0), factorial(5), factorialRecursive(5)); // 1n 120n 120
11console.log(factorial(25)); // 15511210043330985984000000n - exact
12console.log(factorialRecursive(25)); // 1.5511210043330986e+25 - Number loses digits
13console.log(factorialRecursive(171)); // Infinity
14
15try {
16 factorial(-3);
17} catch (e) {
18 console.log(e.message); // n must be a non-negative integer
19}
20
21// Follow-up: trailing zeros of n! without computing it
22function trailingZeros(n) {
23 let count = 0;
24 for (let p = 5; p <= n; p *= 5) count += Math.floor(n / p);
25 return count;
26}
27console.log(trailingZeros(100), String(factorial(100)).match(/0*$/)[0].length); // 24 24
28
29// Combinations with factorials: nCr
30const nCr = (n, r) => factorial(n) / (factorial(r) * factorial(n - r));
31console.log(nCr(10, 3)); // 120n

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app