Lesson 11 of 15

Recurrence Relations

Counting with Recurrences

A recurrence relation defines a sequence by expressing ana_n in terms of previous terms. Combined with initial conditions, it uniquely determines the sequence.

Linear Recurrences

A linear homogeneous recurrence with constant coefficients: an=c1an1+c2an2++ckanka_n = c_1 a_{n-1} + c_2 a_{n-2} + \cdots + c_k a_{n-k}

Characteristic equation: substitute an=rna_n = r^n to get rk=c1rk1++ckr^k = c_1 r^{k-1} + \cdots + c_k. If roots r1,r2,r_1, r_2, \ldots are distinct, the solution is: an=α1r1n+α2r2n+a_n = \alpha_1 r_1^n + \alpha_2 r_2^n + \cdots

Fibonacci: Fn=Fn1+Fn2F_n = F_{n-1} + F_{n-2}, F0=0F_0=0, F1=1F_1=1. Characteristic roots r=1±52r = \frac{1 \pm \sqrt{5}}{2} (golden ratio ϕ\phi and its conjugate).

Towers of Hanoi

T(n)=2T(n1)+1T(n) = 2T(n-1) + 1, T(1)=1T(1)=1. Closed form: T(n)=2n1T(n) = 2^n - 1.

def solve_linear_recurrence(coeffs, initial, n):
    seq = list(initial)
    k = len(coeffs)
    while len(seq) <= n:
        next_val = sum(coeffs[i] * seq[-(i+1)] for i in range(k))
        seq.append(next_val)
    return seq[n]

# Fibonacci: coeffs=[1,1], initial=[0,1]
print(solve_linear_recurrence([1, 1], [0, 1], 10))  # 55

Your Task

Implement solve_fibonacci, solve_linear_recurrence, and towers_of_hanoi_count.

Pyodide loading...
Loading...
Click "Run" to execute your code.