← Back to KaleidoScope

Published on November 28, 202554 min read

One Problem, Three Algorithms

A comparative exploration of how different algorithms approach the same problem and what their trade-offs reveal about computational reasoning.

One Problem, Three Algorithms

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 Mathematics of a Simple Sequence

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=1F_0 = 0,\qquad F_1 = 1

For every subsequent term:

Fn=Fn−1+Fn−2,n≥2F_n = F_{n-1} + F_{n-2},\qquad n \geq 2

The resulting sequence begins with:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34,…0,\ 1,\ 1,\ 2,\ 3,\ 5,\ 8,\ 13,\ 21,\ 34,\ldots

What makes this recurrence particularly useful for our experiment is the dependency between its individual terms. To calculate FnF_n, we need two previous values. How we obtain, retain and reuse those values is a computational decision rather than a mathematical requirement.

Recursion and the Price of Mathematical Elegance

The most direct translation of the recurrence relation into Python is a recursive function.

untitledPython
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.

Let us examine the recursive computation of F5F_5.

untitledText
F(5)
├── F(4)
│   ├── F(3)
│   │   ├── F(2)
│   │   │   ├── F(1)
│   │   │   └── F(0)
│   │   └── F(1)
│   └── F(2)
│       ├── F(1)
│       └── F(0)
└── F(3)
    ├── F(2)
    │   ├── F(1)
    │   └── F(0)
    └── F(1)

Notice how often the same values appear in different branches of the recursive call tree. Once the function has calculated F3F_3, 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)+1C(n) = C(n-1) + C(n-2) + 1

With the initial conditions:

C(0)=C(1)=1C(0) = C(1) = 1

The exact number of recursive calls is:

C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1

To understand the growth of this function, we can introduce the golden ratio:

φ=1+52\varphi = \frac{1+\sqrt{5}}{2}

Since Fibonacci numbers grow asymptotically as:

Fn∼φn5F_n \sim \frac{\varphi^n}{\sqrt{5}}

The time complexity of our recursive implementation, under a unit-cost arithmetic model, becomes:

T(n)∈Θ(φn)T(n) \in \Theta(\varphi^n)
Fibonacci indexRecursive function calls
515
10177
2021,891
302,692,537
40331,160,281
5040,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.

Iteration: Rethinking the Computational Process

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
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 kk, our variables satisfy the following invariant:

a=Fk,b=Fk+1a = F_k,\qquad b = F_{k+1}

After applying the state transition:

(a,b)⟶(b,a+b)(a,b) \longrightarrow (b,a+b)

We obtain:

(Fk,Fk+1)⟶(Fk+1,Fk+2)(F_k,F_{k+1}) \longrightarrow (F_{k+1},F_{k+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)T(n) \in \Theta(n)

It also maintains a constant number of numeric variables:

S(n)∈Θ(1)S(n) \in \Theta(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.

Memoisation: Giving Recursion a Memory

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
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
fibonacci_memoized.cache_clear()

result = fibonacci_memoized(10)

print(result)
print(fibonacci_memoized.cache_info())

Expected output:

untitledText
55
CacheInfo(hits=8, misses=11, maxsize=None, currsize=11)

The eleven cache misses correspond to the distinct subproblems from F0F_0 to F10F_{10}. Subsequent requests for previously calculated values can be satisfied directly from the cache.

The number of distinct subproblems for n≥2n \geq 2 is:

D(n)=n+1D(n) = n+1

Assuming constant-cost arithmetic and typical constant-time cache operations, we obtain:

T(n)∈Θ(n)T(n) \in \Theta(n)

The improvement comes at the expense of storing intermediate results and maintaining the recursive call stack:

S(n)∈Θ(n)S(n) \in \Theta(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.

Three Algorithms, Three Computational Profiles

PropertyNaive recursionIterationMemoisation
Time complexityΘ(φn)\Theta(\varphi^n)Θ(n)\Theta(n)Θ(n)\Theta(n)
Auxiliary spaceΘ(n)\Theta(n)Θ(1)\Theta(1)Θ(n)\Theta(n)
Execution strategyRecursiveSequentialCached recursion
Intermediate resultsRecomputedTwo consecutive values retainedStored in cache
Recursive call stackYesNoYes

These estimates use a unit-cost arithmetic model. Actual Python execution also depends on integer size, function-call overhead, cache operations and interpreter limitations.

A Small Computational Experiment

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.

untitledPython
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.

Between the Lines

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.

Intersections

  • Under which conditions would you favour recursion over iteration?
  • Does mathematical elegance influence your choice of algorithm?
  • How would the comparison change if we included fast doubling or matrix exponentiation?
  • Should algorithmic complexity be introduced earlier in programming education?

Discussion

Share your perspective.

0comments

There are no approved comments yet. Start the discussion.