JavaScriptEasy
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 casen <= 1. Clear, but uses O(n) stack and can overflow for very largen. - Memoised / table: useful when you need many factorials (for combinations
nCr = n! / (r! (n-r)!)). reduceover 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
Numberis exact only up to2^53 - 1;18!is the largest factorial that fits exactly (19!loses precision).171!exceedsNumber.MAX_VALUEand becomesInfinity.BigIntkeeps 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 mfor largento 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}78const factorialRecursive = (n) => (n <= 1 ? 1 : n * factorialRecursive(n - 1)); // fine for small n910console.log(factorial(0), factorial(5), factorialRecursive(5)); // 1n 120n 12011console.log(factorial(25)); // 15511210043330985984000000n - exact12console.log(factorialRecursive(25)); // 1.5511210043330986e+25 - Number loses digits13console.log(factorialRecursive(171)); // Infinity1415try {16 factorial(-3);17} catch (e) {18 console.log(e.message); // n must be a non-negative integer19}2021// Follow-up: trailing zeros of n! without computing it22function 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 242829// Combinations with factorials: nCr30const 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.