Recursion

O(2ⁿ)·O(n) space
fib(10)n = 10
  • Running

Call fib(10).

Call fib(10).
  1. 1to find the nth Fibonacci number
  2. 2if n is 0 or 1, that is the answer already
  3. 3otherwise add the two before it together
  4. 4work out the (n-1)th the same way
  5. 5work out the (n-2)th the same way
  6. 6hand back their sum
Calls
1
Deepest stack
1
Additions
0

Complexity

BestO(2ⁿ)
AverageO(2ⁿ)
WorstO(2ⁿ)
Extra spaceO(n)
2·F(n+1) at n=10 predicts 178; this run took 1.

Fibonacci, naive

Naive Fibonacci computes the nth Fibonacci number by adding the two before it, each found the same recursive way, with 0 and 1 as base cases. Every call above the base cases makes two further calls, so the recursion forms a tree rather than the single chain factorial does.

When it is the right choice

There is no honest case for using this version: it recomputes fib(k) for every smaller k as many times as it is needed on the way to fib(n), which grows exponentially with n. It exists on this page to make that waste visible and countable — see it raced against the memoised version below, which keeps the identical logic but remembers what it has already worked out.

How it works

Worth noticing

Cost

Best
O(2ⁿ)
Average
O(2ⁿ)
Worst
O(2ⁿ)
Extra space
O(n)
Largest input
n = 16

The largest input is a pedagogical ceiling rather than a technical one. This algorithm makes 2·F(n+1) calls, and past n = 16 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