Mental model
The Fibonacci numbers are defined by a recurrence: F(0) = 0, F(1) = 1, and F(n) = F(n − 1) + F(n − 2). Translated literally into code:
fib(n):
if n < 2: return n
return fib(n - 1) + fib(n - 2)
This is correct, and hopelessly slow. Draw the calls for fib(5): fib(5) calls fib(4) and fib(3); fib(4) calls fib(3) again and fib(2); each fib(3) calls fib(2) again… The same questions are asked many times, and every time the whole subtree beneath them is recomputed. Those repeated questions are overlapping subproblems, and they are the signal that dynamic programming applies.
The lab shows three rows: the call stack, the stored values (empty for the naive version: it stores nothing), and a counter of how many times fib(k) has been called for each k. Run the Naive: fib(6) preset and watch fib(2) get called five times and fib(1) eight times.
How bad is the naive version?
Let C(n) be the number of calls fib(n) makes, including itself. One call plus the calls of both children:
C(0) = C(1) = 1, C(n) = 1 + C(n − 1) + C(n − 2)
Adding 1 to both sides shows that C(n) + 1 follows the Fibonacci recurrence, which gives exactly C(n) = 2·F(n + 1) − 1: 25 calls for n = 6, 465 for n = 12, 2,692,537 for n = 30. Since F(n) = (φⁿ − ψⁿ)/√5 with φ = (1 + √5)/2 ≈ 1.618 and |ψ| < 1, F(n) is the nearest integer to φⁿ/√5, so
- the naive version takes Θ(φⁿ) time: each increase of n multiplies the work by about 1.618;
- O(2ⁿ) is also a correct upper bound (each call makes at most two more), but it is not tight. Claiming Θ(2ⁿ) would be wrong.
The stack depth, by contrast, is only n: one path of the recursion tree at a time. The lab caps the naive version at n = 12 so the trace stays short; the other two go to 30.
A finer point: fib(k) is called exactly F(n − k + 1) times for k ≥ 1 (and fib(0) F(n − 1) times). Read right to left, the counts row in the lab is itself the Fibonacci sequence 1, 1, 2, 3, 5, … (except for fib(0)).
Memoization: top-down dynamic programming
Keep the recursion, but remember every answer the first time it is computed:
fib(n, memo):
if n < 2: return n
if memo[n] is known: return memo[n] # reuse
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]
Now fib(n − 1) computes everything below it once, and when fib(n) then asks for fib(n − 2) the answer is already stored. Every fib(k) does real work once and is otherwise answered in O(1). The exact count is 2n − 1 calls for n ≥ 1: 59 for n = 30 instead of 2.7 million. Time O(n), memory O(n) for the memo plus O(n) stack frames.
The order of the two checks matters little here, but the order of the two recursive calls matters for depth: computing fib(n − 1) first walks straight down to the base case, so the stack reaches depth n once.
Tabulation: bottom-up dynamic programming
The memoized recursion fills memo[2], memo[3], … in increasing order anyway. Do exactly that with a loop and no recursion at all:
table[0] = 0; table[1] = 1
for i in 2 .. n:
table[i] = table[i - 1] + table[i - 2]
return table[n]
The loop order guarantees that both inputs of every entry are filled before it is computed: that is the key requirement for any bottom-up table. n − 1 additions, O(n) time, no stack. Because each entry only needs the two before it, you can keep just two variables and use O(1) memory; the teaching version keeps the full table so the lab can show it.
| Strategy | Calls | Additions | Time | Extra memory |
|---|---|---|---|---|
| Naive recursion | 2·F(n+1) − 1 | F(n+1) − 1 | Θ(φⁿ) | O(n) stack |
| Memoized recursion | 2n − 1 | n − 1 | Θ(n) | O(n) memo + O(n) stack |
| Table | 0 | n − 1 | Θ(n) | O(n) table, or O(1) with two variables |
(Counts for n ≥ 2; the costs assume O(1) additions, true for fixed-width integers.)
The general recipe
Fibonacci is the smallest example of a pattern you will use for every dynamic programming problem:
- State: what a subproblem is (here, one index k).
- Transition: how a state's answer combines smaller states' answers (F(k − 1) + F(k − 2)).
- Base cases: states answered directly (k = 0 and k = 1).
- Order: top-down with a memo, or bottom-up in an order where dependencies come first.
Memoization is often easier to write (it is the recursion plus three lines) and only computes the states that are actually needed. Tabulation avoids recursion depth limits and call overhead, and makes space optimisations visible. The two problems in the bank that use exactly this 1D shape are How many ways up the stairs? (Fibonacci in disguise) and Collect the most without taking neighbours (a max instead of a sum). The next lesson, 0/1 knapsack, uses a two-dimensional state.
Overflow: Fibonacci numbers grow fast
F(n) grows like φⁿ, so it runs out of bits quickly:
| Type | Last F(n) that fits | Value |
|---|---|---|
signed 32-bit (int) |
F(46) | 1,836,311,903 |
signed 64-bit (long, int64_t) |
F(92) | 7,540,113,804,746,346,429 |
| unsigned 64-bit | F(93) | 12,200,160,415,121,876,738 |
The C#, Java and C++ implementations use 64-bit integers and reject n > 92 rather than return a
wrong number. Without that check, C# and Java would silently wrap around to a negative value (both
default to unchecked integer arithmetic), and C++ would have undefined behaviour, because signed
overflow is undefined. Python's integers have unlimited precision, so the Python version has no
upper bound; tabulated(1000) is a 209-digit number. For larger values in the other languages use
System.Numerics.BigInteger (C#), java.math.BigInteger (Java) or a big-integer library (C++).
Language notes
- Python:
@functools.cachememoizes a function in one line. Memoized recursion still hits the recursion limit (1000 frames by default) for large n; the Python test calls memoized(n) with n a little past the limit and getsRecursionError, while tabulated(n) works. - C#: no built-in memoize attribute; use an array (as here) or a
Dictionary<int, long>. - Java: avoid memoizing with
HashMap.computeIfAbsentwhose mapping function recurses into the same map: the documentation forbids modifying the map from the mapping function, andHashMapthrowsConcurrentModificationExceptionwhen it detects this (on a best-effort basis). Use an array or an explicit get/put. - C++: a
std::vector<std::int64_t>memo initialised to −1;-1works as "unknown" because no Fibonacci number is negative.
The teaching implementation
All four languages have Naive, Memoized and Tabulated with a Calls counter that matches the
lab's Calls metric. They read one shared fixture with values and exact call counts from n = 0 to
92 (including the last values that fit in 32 and 64 bits), and compare every n up to 92 with an exact
loop (BigInteger in C# and Java, unsigned 64-bit in C++, Python ints).
Common mistakes
- Calling it "O(2ⁿ)" and stopping there. True as an upper bound; the tight bound is Θ(φⁿ).
- A memo that is never written, or written after returning: still exponential.
- Using 0 as the "unknown" marker when 0 is a valid answer (F(0) = 0). Here the base case
catches it, but in other problems it silently disables the memo; use −1,
Noneor a separate flag. - A table filled in the wrong order, reading entries that are not computed yet.
- Ignoring overflow: F(47) in a 32-bit
intis negative in C# and Java and undefined in C++.
Edge cases
- n = 0 and n = 1 are base cases: one call, no addition, no table needed.
- Negative n is rejected in every language.
Worked practice
1. How many calls does naive fib(10) make, and how many does the memoized version make?
Answer
Naive: 2·F(11) − 1 = 2·89 − 1 = 177. Memoized: 2·10 − 1 = 19.
2. Roughly how much longer does naive fib(40) take than naive fib(30)?
Answer
About φ¹⁰ ≈ 123 times longer: the call count goes from 2.7 million to about 331 million.
3. Rewrite the table version with O(1) extra space.
Answer
Keep the last two values: a, b = 0, 1, then repeat n times a, b = b, a + b, and return a.
Each step overwrites the value that is no longer needed.
Summary
- Naive recursion on an overlapping recurrence repeats work: Fibonacci makes 2·F(n+1) − 1 calls, Θ(φⁿ).
- Memoization (top-down) stores each answer once: 2n − 1 calls, Θ(n).
- Tabulation (bottom-up) fills the answers in dependency order with a loop: Θ(n), no stack, O(1) space possible.
- Dynamic programming = state + transition + base cases + an evaluation order.
- Fibonacci overflows 32 bits after F(46) and 64 bits after F(92); Python's integers do not overflow.