The Fibonacci sequence has always struck me as an excellent example of how a relatively simple mathematical definition can lead to rather different computational implementations. Each number is obtained by adding the two preceding numbers. The mathematical rule could hardly be simpler, yet its translation into executable code opens up an interesting discussion about recursion, iteration, memory management and computational efficiency.
I am particularly fond of recursive solutions because of the elegance with which they can express mathematical relationships. There is something intellectually satisfying about an implementation that closely resembles the mathematical definition of a problem. Unfortunately, mathematical elegance and computational efficiency do not always go hand in hand. The naive recursive implementation of the Fibonacci sequence demonstrates this beautifully, producing an extraordinary amount of redundant computation from just a few innocent-looking lines of Python.
For this article, I have chosen three approaches to computing Fibonacci numbers: naive recursion, iteration and recursion with memoisation. The mathematical problem remains unchanged, as does the expected result. What changes is the organisation of the computational process, the number of operations performed and the way intermediate results are handled in memory.
Rather than simply comparing three code snippets and declaring one implementation superior, I want to examine what actually happens during execution. We will look at recursive call trees, mathematical recurrence relations, stack memory and asymptotic complexity, followed by a small computational experiment in Python. After all, the most interesting differences between algorithms are not necessarily visible in the source code itself.
The Fibonacci sequence is defined by a recurrence relation in which each term depends on the two preceding terms.
The initial conditions are:
F0=0,F1=1
For every subsequent term:
Fn=Fn−1+Fn−2,n≥2
The resulting sequence begins with:
0,1,1,2,3,5,8,13,21,34,…
What makes this recurrence particularly useful for our experiment is the dependency between its individual terms. To calculate Fn, we need two previous values. How we obtain, retain and reuse those values is a computational decision rather than a mathematical requirement.
The most direct translation of the recurrence relation into Python is a recursive function.
untitledPython
1234567891011
def fibonacci_recursive(n: int) -> int:
if n < 0:
raise ValueError("n must be non-negative")
if n <= 1:
return n
return (
fibonacci_recursive(n - 1)
+ fibonacci_recursive(n - 2)
)
The resemblance between the mathematical definition and its implementation is almost perfect. Unfortunately, the resemblance tells us very little about what happens during execution.
Notice how often the same values appear in different branches of the recursive call tree. Once the function has calculated F3, nothing in our implementation prevents it from calculating precisely the same value again.
We can describe the total number of function calls using another recurrence relation:
C(n)=C(n−1)+C(n−2)+1
With the initial conditions:
C(0)=C(1)=1
The exact number of recursive calls is:
C(n)=2Fn+1−1
To understand the growth of this function, we can introduce the golden ratio:
φ=21+5
Since Fibonacci numbers grow asymptotically as:
Fn∼5φn
The time complexity of our recursive implementation, under a unit-cost arithmetic model, becomes:
T(n)∈Θ(φn)
Fibonacci index
Recursive function calls
5
15
10
177
20
21,891
30
2,692,537
40
331,160,281
50
40,730,022,147
There is a certain irony in an implementation consisting of so few lines of code generating billions of function calls. The mathematical elegance remains intact. The computational efficiency, considerably less so.
The recurrence relation does not require us to reconstruct the entire sequence every time we need another Fibonacci number. It merely establishes a dependency between three consecutive terms.
Once we have calculated two consecutive values, we possess all the information required to calculate the next one.
untitledPython
12345678910
def fibonacci_iterative(n: int) -> int:
if n < 0:
raise ValueError("n must be non-negative")
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
The mathematical relationship has not changed. What has changed is the representation of the computational state.
At iteration k, our variables satisfy the following invariant:
a=Fk,b=Fk+1
After applying the state transition:
(a,b)⟶(b,a+b)
We obtain:
(Fk,Fk+1)⟶(Fk+1,Fk+2)
This invariant allows us to reason about the correctness of the implementation independently of any particular execution result.
Under a unit-cost arithmetic model, the algorithm performs a linear number of operations:
T(n)∈Θ(n)
It also maintains a constant number of numeric variables:
S(n)∈Θ(1)
The distinction between a constant number of variables and constant physical memory consumption deserves some attention. Python integers have arbitrary precision. As Fibonacci numbers grow, their binary representations require additional memory, and arithmetic operations become increasingly expensive. Our complexity estimates therefore describe the algorithm under a simplified arithmetic model rather than the complete behaviour of the Python runtime.
I would not abandon recursion merely because its naive implementation is inefficient. The recursive formulation has a useful mathematical structure. Its principal weakness lies in the repeated evaluation of identical subproblems.
What if we retained the results of previous computations?
Python provides a convenient mechanism through the functools module.
untitledPython
123456789101112131415
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci_memoized(n: int) -> int:
if n < 0:
raise ValueError("n must be non-negative")
if n <= 1:
return n
return (
fibonacci_memoized(n - 1)
+ fibonacci_memoized(n - 2)
)
The recursive definition remains almost identical to our original implementation. The decorator, however, changes the behaviour of the computational process by introducing a cache.
When the function receives an argument for which a result already exists, Python retrieves the stored value instead of evaluating the recursive expression again.
untitledPython
123456
fibonacci_memoized.cache_clear()
result = fibonacci_memoized(10)
print(result)
print(fibonacci_memoized.cache_info())
The eleven cache misses correspond to the distinct subproblems from F0 to F10. Subsequent requests for previously calculated values can be satisfied directly from the cache.
The number of distinct subproblems for n≥2 is:
D(n)=n+1
Assuming constant-cost arithmetic and typical constant-time cache operations, we obtain:
T(n)∈Θ(n)
The improvement comes at the expense of storing intermediate results and maintaining the recursive call stack:
S(n)∈Θ(n)
Memoisation is particularly interesting because it preserves the recursive mathematical formulation while changing the execution strategy. It also illustrates one of the fundamental principles of dynamic programming: overlapping subproblems need not be solved repeatedly.
These estimates use a unit-cost arithmetic model. Actual Python execution also depends on integer size, function-call overhead, cache operations and interpreter limitations.
Rather than leaving the comparison entirely within the domain of asymptotic analysis, I want to examine the execution behaviour of these three implementations under comparable conditions.
from functools import lru_cache
from statistics import median
from timeit import repeat
def fibonacci_recursive(n):
if n <= 1:
return n
return (
fibonacci_recursive(n - 1)
+ fibonacci_recursive(n - 2)
)
def fibonacci_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
@lru_cache(maxsize=None)
def fibonacci_memoized(n):
if n <= 1:
return n
return (
fibonacci_memoized(n - 1)
+ fibonacci_memoized(n - 2)
)
def run_memoized(n):
fibonacci_memoized.cache_clear()
return fibonacci_memoized(n)
algorithms = {
"Recursion": fibonacci_recursive,
"Iteration": fibonacci_iterative,
"Memoisation": run_memoized,
}
sizes = [5, 10, 15, 20, 25, 30]
for n in sizes:
expected = fibonacci_iterative(n)
print(f"\nFibonacci index: {n}")
for name, algorithm in algorithms.items():
assert algorithm(n) == expected
measurements = repeat(
lambda: algorithm(n),
repeat=5,
number=1
)
duration = median(measurements)
print(f"{name:15s}: {duration:.9f}s")
I deliberately clear the cache before each memoised computation. Measuring an already cached result would introduce a different experimental condition and tell us considerably less about the cost of calculating the sequence from scratch.
The median of five measurements provides a simple summary of execution time, although a more rigorous performance study would require additional repetitions, controlled execution conditions and an examination of measurement variability. For particularly short operations, increasing the number of executions per measurement would also improve timing resolution.
The experiment should reveal the rapidly increasing cost of naive recursion, while iteration and memoisation exhibit considerably slower growth. Whether the two linear algorithms perform equally well in practice is another matter. Asymptotic equivalence does not eliminate differences in function-call overhead, memory allocation or cache management.
What I find fascinating about this comparison is the journey from a mathematical definition to three distinct computational processes. The recurrence relation remains unchanged throughout the experiment, yet the organisation of computation produces radically different consequences.
There is also an educational question here. When teaching programming, we frequently concentrate on whether students have implemented a function correctly. I would be equally interested in whether they can explain why their implementation behaves the way it does, which computational resources it consumes and how a different strategy might change those requirements.
A student who understands the recursive call tree has acquired something considerably more valuable than the ability to reproduce a Fibonacci function. They have encountered overlapping subproblems, mathematical dependencies, computational complexity and the possibility of reorganising a calculation without altering its mathematical meaning.
The Fibonacci sequence is a modest example. The intellectual principles behind these three implementations extend far beyond it.