Recursion

O(n)·O(n) space
factorial(5)n = 5
  • Running

Call factorial(5).

Call factorial(5).
  1. 1to find the factorial of n
  2. 2if n is 0, the answer is 1 already
  3. 3otherwise, work out the factorial of n minus 1 first
  4. 4multiply n by that result and hand it back
Calls
1
Deepest stack
1
Multiplications
0

Complexity

BestO(n)
AverageO(n)
WorstO(n)
Extra spaceO(n)
n + 1 at n=5 predicts 6; this run took 1.

Factorial

Factorial multiplies n by the factorial of n − 1, treating 0 as the base case whose factorial is 1 by definition. Every call above the base case makes exactly one further call, so the recursion forms a single chain rather than a tree.

When it is the right choice

Factorial is the standard first example of recursion precisely because it has nothing else going on: no branching, no repeated work, no state to restore. It is not how a real program should compute a factorial past a tiny n — an iterative loop does the same job without building a stack frame per value, and the recursive version overflows the call stack long before it overflows the numeric type it returns into. Its value here is entirely in what it shows about the stack itself.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n)
Worst
O(n)
Extra space
O(n)
Largest input
n = 20

The largest input is a pedagogical ceiling rather than a technical one. This algorithm makes n + 1 calls, and past n = 20 the run stops being something a person can sit and watch — long before it reaches the step limit the tool enforces.

Worth comparing

All recursive algorithms