"""Fibonacci three ways: naive recursion, memoisation, bottom-up.

Idea
----
F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2). Naive recursion recomputes
the same values exponentially often. Caching results (top-down memoisation)
or filling a table from the bottom up turns it into a linear-time loop. The
bottom-up version only needs the last two values, so space drops to O(1).

This is the "hello world" of dynamic programming: once you see why the naive
call tree explodes, every other DP problem is the same trick.

Complexity
----------
Naive:     O(phi^n) time, O(n) stack
Memoised:  O(n) time, O(n) space
Bottom-up: O(n) time, O(1) space
"""

from functools import cache


def fib_naive(n: int) -> int:
    """Exponential-time reference implementation. Keep n small."""
    return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)


@cache
def fib_memo(n: int) -> int:
    """Top-down DP with an automatic cache."""
    return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)


def fib(n: int) -> int:
    """Bottom-up DP keeping only the last two values."""
    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
