Full answer
The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, and each number is the sum of the previous two.
Naive recursion, fib(n) = fib(n - 1) + fib(n - 2), looks like the definition, but it calls itself twice and repeats the same subproblems. The number of calls grows exponentially, roughly 1.6 to the power of n. fib(40) already takes noticeable time, and fib(100) would never finish.
Better versions:
- Memoization: store computed values in a Map or an array. Each value is computed once, so time is O(n), and space is O(n) for the cache and the call stack.
- Iteration: keep two variables,
aandb, and update them in a loop. Time is O(n) and space is O(1). This is the version to prefer in practice. - Fast doubling or matrix exponentiation gives O(log n) arithmetic steps, and is a good bonus answer.
Factorial, n! = n * (n - 1) * ... * 1, is naturally recursive, but a loop is just as clear and avoids stack overflow for large inputs. Define 0! = 1, and reject negative and non-integer inputs.
Number limits: JavaScript numbers are 64-bit floats and are exact only up to Number.MAX_SAFE_INTEGER (2 to the 53 minus 1). fib(79) is already beyond the safe range, and 171! overflows to Infinity. Use BigInt for exact large results, with the n suffix and BigInt(...) for conversion. Note that you cannot mix BigInt and Number in one expression.
For recursive solutions, mention the call stack limit, about ten thousand frames, and that JavaScript engines do not guarantee tail call optimization.
let naiveCalls = 0;
function fibNaive(n) {
naiveCalls++;
return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2);
}
function fibMemo(n, memo = new Map()) {
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo.set(n, value);
return value;
}
function fibLoop(n) {
let [a, b] = [0n, 1n];
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
function factorial(n) {
if (!Number.isInteger(n) || n < 0) throw new RangeError('n must be a non-negative integer');
let result = 1n;
for (let i = 2n; i <= BigInt(n); i++) result *= i;
return result;
}
console.log([0, 1, 2, 3, 4, 5, 10, 20].map((n) => fibMemo(n)));
fibNaive(20);
console.log('naive calls for n = 20:', naiveCalls);
naiveCalls = 0;
fibNaive(25);
console.log('naive calls for n = 25:', naiveCalls);
console.log(fibLoop(90), fibLoop(300).toString().length + ' digits');
console.log('number version loses precision:', fibMemo(90), 'versus BigInt', fibLoop(90));
console.log(factorial(0), factorial(5), factorial(20), String(factorial(25)));
console.log('171! as a Number:', Number(factorial(171)), 'safe limit:', Number.MAX_SAFE_INTEGER);
try {
factorial(-1);
} catch (error) {
console.log(error.name);
}Run with Node.js v24.22.1 as js-120.js; two runs gave identical output. Output: [ 0, 1, 1, 2, 3, 5, 55, 6765 ] naive calls for n = 20: 21891 naive calls for n = 25: 242785 2880067194370816120n 63 digits number version loses precision: 2880067194370816000 versus BigInt 2880067194370816120n 1n 120n 2432902008176640000n 15511210043330985984000000 171! as a Number: Infinity safe limit: 9007199254740991 RangeError
Key points
- Naive recursive Fibonacci is exponential because it repeats subproblems.
- Memoization gives O(n); a loop with two variables gives O(n) time and O(1) space.
- Fast doubling gives O(log n) steps.
- Numbers lose exactness past 2 to the 53 minus 1; use BigInt for large results and do not mix types.
- Recursion depth is limited and tail calls are not guaranteed, so prefer loops for large inputs.
Common mistakes
- Using naive recursion for large n.
- Mixing BigInt and Number in one expression and getting a TypeError.
- Forgetting that 0! is 1 and that negative input must be rejected.
- Trusting results beyond Number.MAX_SAFE_INTEGER.
Follow-ups
- How does fast doubling compute Fibonacci in O(log n)?
- What is the call stack limit, and what happens when recursive factorial exceeds it?
- Why do JavaScript engines not guarantee tail call optimization?
Tips
- Show the call count to prove why the naive version is slow.
- Present the loop as the practical answer and memoization as the teaching answer.
- Mention BigInt as soon as large results appear.