Module contents
Lesson 12 of 22Core 105 min

Recurrences: modelling and solving

Model a recursive algorithm or counting problem with a recurrence and solve it by unrolling, substitution with induction, recursion trees, characteristic polynomials, particular solutions and matrix form. The master theorem is deferred to m08.

After this lesson you can

  • Model recursive algorithm costs and counting problems with recurrences
  • Solve recurrences by unrolling and verify by induction using substitution
  • Estimate divide-and-conquer growth using recursion trees
  • Solve constant-coefficient linear recurrences including repeated and complex roots
  • Compute distant terms in logarithmic time with a companion matrix and fast exponentiation

Before you start

Motivation: sequences defined by themselves

Many quantities important in computing are not known directly, but through how they relate to smaller versions of themselves.

  • Recursive algorithm cost. Mergesort sorts nn elements by sorting two halves and merging with about nn comparisons. If T(n)T(n) is cost, code directly says only T(n)=2T(n/2)+nT(n) = 2T(n/2) + n. “How long?” asks “what function satisfies that equation?”
  • Number of size-nn objects. Binary strings of length nn without consecutive ones, hallway tilings or legal game positions are counted by decomposing a large object into smaller objects of the same kind. Decomposition relates size-nn counts to smaller counts.
  • Systems evolving in time. An autoregressive model xt=ϕ1xt−1+ϕ2xt−2+εtx_t = \phi_1 x_{t-1} + \phi_2 x_{t-2} + \varepsilon_t, digital filter or state layer of a model such as S4 or Mamba, ht=Aht−1+Bxt\vb{h}_t = \mat{A}\vb{h}_{t-1} + \mat{B}\vb{x}_t, calculates the present from the past. Whether they explode, decay or oscillate depends on a few numbers you will learn to read.

Each case has two tasks. First model: turn an algorithm or counting problem into a precise equation with correct base cases. Second solve: find a closed form or growth order and prove it correct. This lesson covers both with unrolling verified by induction, recursion trees, constant-coefficient linear recurrence theory and matrix form. The general recursion-tree result, the master theorem, belongs to the algorithms module; here we build its intuition and proofs.

Modeling: from an algorithm or count to a recurrence

A recurrence and initial values define a unique sequence: by strong induction, sequences agreeing on a0,…,an0−1a_0, \dots, a_{n_0 - 1} and satisfying the same rule agree for every nn. This also justifies that a terminating recursive function computes something well-defined, the correctness of recursive algorithms from lesson 8. Initial values are part of the recurrence, not a detail: an=2an−1+1a_n = 2a_{n-1} + 1 with a0=0a_0 = 0 and with a0=5a_0 = 5 give different sequences. Three models recur throughout the lesson.

Towers of Hanoi

Three pegs and nn differently sized disks stand on the first, largest to smallest. Move them all to the third one disk at a time, never placing a disk on a smaller one. The recursive solution is nearly forced: to move nn disks from A to C, move the top n−1n - 1 from A to B (using C as auxiliary), move the largest A to C, then move the n−1n - 1 from B to C. If T(n)T(n) counts moves,

T(0)=0,T(n)=2T(n−1)+1(n≥1).T(0) = 0, \qquad T(n) = 2T(n-1) + 1 \quad (n \ge 1).

The algorithm taking T(n)T(n) moves does not show it cannot be improved. A lower bound is needed, and the same recurrence supplies it.

Proof

The algorithm gives M(n)≤T(n)M(n) \le T(n). For the reverse show M(n)≥2M(n−1)+1M(n) \ge 2M(n-1) + 1 for n≥1n \ge 1. Any solution must move the largest disk at least once. Just before its first move, from A to another peg XX, the remaining n−1n - 1 disks can be neither on it at A nor on XX (the largest cannot sit on smaller disks), so they all sit on the third peg: a tower of n−1n - 1 disks has been transferred, costing at least M(n−1)M(n-1) moves (the largest disk beneath everything neither helps nor hinders). Just after its last move, placing it on C, the n−1n - 1 disks are all on another peg and must finish atop it: at least another M(n−1)M(n-1) moves. The blocks and largest-disk move are disjoint, so M(n)≥2M(n−1)+1M(n) \ge 2M(n-1) + 1. Since M(0)=T(0)=0M(0) = T(0) = 0, immediate induction gives M(n)≥T(n)M(n) \ge T(n).

∎

The next figure shows the solution move by move and below it the same recurrence as a strip: each bar has the moved disk’s color. Inspect the strip before unrolling: it is the recurrence drawn.

InteractiveHanoi and its recurrence
A (origen)BC (destino)1234T(3)T(3)
T(4)=T(4) =21 T(3)2^{1}\,T(3)+202^{0}=2⋅7+1=15= 2\cdot 7 + 1 = 15
Each box 2j2^{j} has the color of disk 4−j4 - j and counts its moves; brackets mark the 212^{1} copies of the solution with 33 disks.
4
15 / 15
1
Move15 of 2⁴ − 1 = 15
Lastdisk 1: B → C
disk 1: 8 / 8disk 2: 4 / 4disk 3: 2 / 2disk 4: 1 / 1
Finished in 24−1=152^{4} - 1 = 15 moves. Disk dd moved 24−d2^{4 - d} times: the sum 1+2+⋯+231 + 2 + \cdots + 2^{3} in the expansion.
Above, the recursive solution move by move. Below, the 2n−12^n - 1 moves in order; each bar has the moved disk's color and height increasing with disk size. Slider kk unrolls the recurrence kk times: T(n)=2k T(n−k)+2k−1+⋯+2+1T(n) = 2^k\,T(n-k) + 2^{k-1} + \cdots + 2 + 1. Braces mark 2k2^k copies of the n−kn - k disk solution, dots the isolated moves of the kk largest disks. Each term 2j2^j in a box colored for disk n−jn - j counts that disk's moves exactly. At k=nk = n no copies remain and the sum is 1+2+⋯+2n−1=2n−11 + 2 + \cdots + 2^{n-1} = 2^n - 1.

The strip resembles ruler marks: disk 1 moves on odd-numbered moves, disk 2 on twice an odd number, and generally move mm uses disk 1+ν2(m)1 + \nu_2(m), where ν2(m)\nu_2(m) counts trailing binary zeros of mm. This explains why disk dd moves exactly 2n−d2^{n-d} times.

Strings without consecutive ones

Let bnb_n count binary strings of length nn without substring 1111. Classify a valid length-n≥2n \ge 2 string by last symbol. Ending in 00, the prefix is any valid string of length n−1n - 1, and conversely: bn−1b_{n-1} strings. Ending in 11, the penultimate symbol must be 00, and before the final 0101 lies any valid length-n−2n - 2 string: bn−2b_{n-2} strings. Cases are disjoint and exhaustive, so the counting principles sum rule gives

b0=1,b1=2,bn=bn−1+bn−2(n≥2).b_0 = 1, \quad b_1 = 2, \qquad b_n = b_{n-1} + b_{n-2} \quad (n \ge 2).

This is Fibonacci’s recurrence with different initial conditions: bn=Fn+2b_n = F_{n+2} if F0=0F_0 = 0, F1=1F_1 = 1. Two modeling details matter. b0=1b_0 = 1 counts the empty string and makes the rule work for n=2n = 2: b2=3b_2 = 3 (0000, 0101, 1010). The decomposition must be a bijection between length-nn strings and the disjoint union of lengths n−1n - 1 and n−2n - 2; if one case could be built in two ways the sum would overcount.

Mergesort cost

Mergesort splits a list into halves of ⌊n/2⌋\lfloor n/2 \rfloor and ⌈n/2⌉\lceil n/2 \rceil, recursively sorts each and merges. Merging sorted lists totaling nn elements costs at most n−1n - 1 comparisons, attained when both lists are exhausted together. Worst-case comparisons therefore satisfy

W(1)=0,W(n)=W(⌈n/2⌉)+W(⌊n/2⌋)+n−1(n≥2).W(1) = 0, \qquad W(n) = W(\lceil n/2 \rceil) + W(\lfloor n/2 \rfloor) + n - 1 \quad (n \ge 2).

This is the exact recurrence. The usual T(n)=2T(n/2)+nT(n) = 2T(n/2) + n simplifies in two steps: remove floors and ceilings and round the nonrecursive term. Both are reasonable but need justification, supplied below. The implementation cell checks W(n)=n⌈log⁡2n⌉−2⌈log⁡2n⌉+1W(n) = n\lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1, a closed form not a clean polynomial times log⁡n\log n because ceilings leave a trace.

Unroll and prove: the substitution method

Unrolling

The most direct way to guess a recurrence solution is repeated application until a pattern emerges. Hanoi:

T(n)=2T(n−1)+1=2(2T(n−2)+1)+1=4T(n−2)+2+1=8T(n−3)+4+2+1    ⋮=2k T(n−k)+(2k−1+⋯+2+1)=2k T(n−k)+2k−1.\begin{aligned} T(n) &= 2T(n-1) + 1 \\ &= 2\big(2T(n-2) + 1\big) + 1 = 4T(n-2) + 2 + 1 \\ &= 8T(n-3) + 4 + 2 + 1 \\ &\;\;\vdots \\ &= 2^k\,T(n-k) + \left(2^{k-1} + \cdots + 2 + 1\right) = 2^k\,T(n-k) + 2^k - 1. \end{aligned}

With k=nk = n, T(n)=2nT(0)+2n−1=2n−1T(n) = 2^n T(0) + 2^n - 1 = 2^n - 1. The figure’s kk slider shows exactly this: 2k2^k copies of the smaller tower and each sum term a large disk’s moves. For 64 disks, 264−1≈1.8×10192^{64} - 1 \approx 1.8\times 10^{19} moves: one per second takes roughly 585 000 million years.

For mergesort, when n=2kn = 2^k is a power of 2 floors disappear and simplified T(n)=2T(n/2)+nT(n) = 2T(n/2) + n, with T(1)=0T(1) = 0, similarly unrolls:

T(n)=2T(n/2)+n=4T(n/4)+n+n=⋯=2j T(n/2j)+j n,T(n) = 2T(n/2) + n = 4T(n/4) + n + n = \cdots = 2^j\,T(n/2^j) + j\,n,

and j=k=log⁡2nj = k = \log_2 n gives T(n)=nlog⁡2nT(n) = n\log_2 n. Each recursion level contributes nn and there are log⁡2n\log_2 n levels.

Conjecture and prove

Unrolling convinces, but ellipses hide an induction. Rigorously prove the conjectured formula by induction using the recurrence itself. This combination is unrolling and the substitution method: conjecture a solution form (unrolling, calculating initial terms or analogy), substitute it into the recurrence as induction hypothesis, and adjust constants to close step and bases.

For Hanoi P(n)P(n) says “T(n)=2n−1T(n) = 2^n - 1.” Base T(0)=0=20−1T(0) = 0 = 2^0 - 1; if T(n−1)=2n−1−1T(n-1) = 2^{n-1} - 1, then T(n)=2(2n−1−1)+1=2n−1T(n) = 2(2^{n-1} - 1) + 1 = 2^n - 1. The method is powerful when the exact solution is unknown and only a bound desired: the conjecture has free constant cc, and proof says which cc works.

When induction fails: subtract a lower-order term

Consider a recursive traversal splitting a problem in halves and doing constant work per call:

T(1)=1,T(n)=T(⌈n/2⌉)+T(⌊n/2⌋)+1(n≥2).T(1) = 1, \qquad T(n) = T(\lceil n/2 \rceil) + T(\lfloor n/2 \rfloor) + 1 \quad (n \ge 2).

Its binary recursion tree has nn leaves, suggesting T(n)=O(n)T(n) = \bigO(n). Try T(n)≤c nT(n) \le c\,n. Assuming the bound for both subproblems,

T(n)≤c⌈n/2⌉+c⌊n/2⌋+1=c n+1.T(n) \le c\lceil n/2 \rceil + c\lfloor n/2 \rfloor + 1 = c\,n + 1.

It fails by 11, and no cc fixes that. The conjecture is true (with c=2c = 2), but the hypothesis is too weak to sustain itself: exactly lesson 5’s strengthening the induction hypothesis. Prove something stronger, T(n)≤c n−dT(n) \le c\,n - d for some d≥0d \ge 0. Now

T(n)≤(c⌈n/2⌉−d)+(c⌊n/2⌋−d)+1=c n−2d+1≤c n−d  ⟺  d≥1.T(n) \le \big(c\lceil n/2 \rceil - d\big) + \big(c\lfloor n/2 \rfloor - d\big) + 1 = c\,n - 2d + 1 \le c\,n - d \iff d \ge 1.

With d=1d = 1 the step closes for any cc, and base T(1)=1≤c−1T(1) = 1 \le c - 1 requires c≥2c \ge 2. Result: T(n)≤2n−1T(n) \le 2n - 1, in fact exact (the tree has nn leaves and n−1n - 1 internal nodes). The subtracted term gives the hypothesis room to absorb each level’s +1+1.

Floors and ceilings

Exact mergesort has floors and ceilings, the solved recurrence did not. Two honest ways bridge the gap.

First, induct directly with floors, as above where ⌈n/2⌉+⌊n/2⌋=n\lceil n/2 \rceil + \lfloor n/2 \rfloor = n kept the calculation exact. With logarithms of ⌊n/2⌋\lfloor n/2 \rfloor, bound ⌊n/2⌋≤n/2\lfloor n/2 \rfloor \le n/2 in the correct direction; the first guided proof does this for T(n)=2T(⌊n/2⌋)+nT(n) = 2T(\lfloor n/2 \rfloor) + n, with the subtlety in choosing base cases rather than the step.

Second, solve at powers of bb and extend by monotonicity.

Proof

Given n≥2n \ge 2, choose k≥1k \ge 1 with 2k≤n<2k+12^k \le n < 2^{k+1}. By monotonicity T(n)≤T(2k+1)≤β g(2k+1)≤Kβ g(2k)≤Kβ g(n)T(n) \le T(2^{k+1}) \le \beta\,g(2^{k+1}) \le K\beta\,g(2^k) \le K\beta\,g(n). Also T(n)≥T(2k)≥α g(2k)≥αK g(2k+1)≥αK g(n)T(n) \ge T(2^k) \ge \alpha\,g(2^k) \ge \frac{\alpha}{K}\,g(2^{k+1}) \ge \frac{\alpha}{K}\,g(n).

∎

Functions nn, n2n^2, nlog⁡2nn\log_2 n and n1.585n^{1.585} satisfy the gg condition (for nlog⁡2nn\log_2 n, g(2n)/g(n)=2(1+1/log⁡2n)≤4g(2n)/g(n) = 2(1 + 1/\log_2 n) \le 4; hence the theorem starts at n=2n = 2, where nlog⁡2nn\log_2 n is positive); 2n2^n does not. Monotonicity of TT must be proved separately, by strong induction. For WW: W(2)−W(1)=1W(2) - W(1) = 1, and for n≥2n \ge 2, if W(m)≤W(m+1)W(m) \le W(m+1) for all m<nm < n, then W(n+1)−W(n)=[W(⌈(n+1)/2⌉)−W(⌈n/2⌉)]+[W(⌊(n+1)/2⌋)−W(⌊n/2⌋)]+1≥1W(n+1) - W(n) = \big[W(\lceil (n+1)/2 \rceil) - W(\lceil n/2 \rceil)\big] + \big[W(\lfloor (n+1)/2 \rfloor) - W(\lfloor n/2 \rfloor)\big] + 1 \ge 1, since each bracket compares equal or consecutive arguments. Thus W(2k)=(k−1)2k+1W(2^k) = (k - 1)2^k + 1, between 12k 2k\tfrac12 k\,2^k and k 2kk\,2^k for k≥1k \ge 1, gives W(n)=Θ(nlog⁡n)W(n) = \Theta(n\log n) for all n≥2n \ge 2, not only powers of 2.

Recursion trees

Mergesort’s unrolling has a geometric interpretation: each recursion level costs nn. A recursion tree makes that explicit for divide-and-conquer recurrences. Each node is a call labeled with work outside recursive calls; children are calls it launches. Total cost is the sum of labels, calculated by levels.

For T(n)=a T(n/b)+ncT(n) = a\,T(n/b) + n^c with T(1)=1T(1) = 1 and n=bLn = b^L:

  • level jj (0≤j≤L0 \le j \le L) has aja^j nodes, each of size n/bjn/b^j;
  • each internal node costs (n/bj)c(n/b^j)^c, so the level costs aj(n/bj)c=nc (a/bc)ja^j (n/b^j)^c = n^c\,(a/b^c)^j;
  • the final level has aL=alog⁡bn=nlog⁡baa^L = a^{\log_b n} = n^{\log_b a} unit-cost leaves, exactly nc(a/bc)Ln^c (a/b^c)^L.

Level costs form a geometric progression with ratio r=a/bcr = a/b^c; everything depends on whether it is below, equal to or above 1.

InteractiveRecursion tree by levels
tree: aʲ subproblems of size n/bʲlevel cost: aʲ (n/bʲ)ᶜj=03232j=1161632j=2888832j=332j=432j=532
2
2
1.00
5
level 5
T(n)=2 T(n/2)+n,r=abc=221=1T(n) = 2\,T(n/2) + n,\quad r = \frac{a}{b^{c}} = \frac{2}{2^{1}} = 1
log⁡ba\log_b a versus cc1.000 = 1.00
T(n)T(n) with n=25=32n = 2^{5} = 32192
Sum of levels 0 to 5192
Root / leaf share16.7 % / 16.7 %
T(n)=Θ(nlog⁡n)T(n) = \Theta\big(n\log n\big)
r=1r = 1: all levels cost the same and the total is one level’s cost times the number of levels, log⁡bn+1\log_b n + 1.
The tree for T(n)=a T(n/b)+ncT(n) = a\,T(n/b) + n^c with n=bLn = b^L, drawn level by level (play the animation); right, each level's cost aj(n/bj)ca^j (n/b^j)^c, leaves orange. Mergesort bars are equal. Switch to Karatsuba: node count grows faster than work per node shrinks, so bars grow downward. Compare ‘root dominates’ (2T(n/2)+n22T(n/2) + n^2) with ‘leaves dominate’ (4T(n/2)+n4T(n/2) + n): both give exactly T(n)=2n2−nT(n) = 2n^2 - n, but cost is at opposite ends. With a=4a = 4 and b=2b = 2, slowly move cc: below c=log⁡24=2c = \log_2 4 = 2 leaves dominate, at c=2c = 2 levels weigh equally, above it the root dominates.
Proof

The sum counts levels; formally induct on LL: T(bL)=a T(bL−1)+bLc=a b(L−1)c∑j=0L−1rj+bLc=bLc(r∑j=0L−1rj+1)=bLc∑j=0LrjT(b^L) = a\,T(b^{L-1}) + b^{Lc} = a\,b^{(L-1)c}\sum_{j=0}^{L-1} r^j + b^{Lc} = b^{Lc}\big(r\sum_{j=0}^{L-1} r^j + 1\big) = b^{Lc}\sum_{j=0}^{L} r^j. Three cases are the geometric series. If r<1r < 1, 1≤∑j=0Lrj<∑j≥0rj=1/(1−r)1 \le \sum_{j=0}^{L} r^j < \sum_{j \ge 0} r^j = 1/(1 - r). If r=1r = 1, the sum is L+1=log⁡bn+1L + 1 = \log_b n + 1. If r>1r > 1, rL≤∑j=0Lrj=rL+1−1r−1<rr−1 rLr^L \le \sum_{j=0}^{L} r^j = \frac{r^{L+1} - 1}{r - 1} < \frac{r}{r - 1}\,r^L, and ncrL=bLcaL/bLc=aL=nlog⁡ban^c r^L = b^{Lc}a^L/b^{Lc} = a^L = n^{\log_b a}.

∎

The theorem gives more than growth: where cost lies. In regime 1 the root alone takes at least fraction 1−r1 - r of the total, so speedups require cheaper combining. In regime 3 leaves take at least 1−1/r1 - 1/r, so fewer subproblems or cheaper bases matter; real Karatsuba and Strassen implementations switch to quadratic or cubic algorithms below a threshold. In regime 2 each level counts.

Recurrencer=a/bcr = a/b^cRegimeSolution
Binary search: T(n/2)+1T(n/2) + 111equalΘ(log⁡n)\Theta(\log n)
Mergesort: 2T(n/2)+n2T(n/2) + n11equalΘ(nlog⁡n)\Theta(n\log n)
Karatsuba: 3T(n/2)+n3T(n/2) + n1.51.5leavesΘ(nlog⁡23)=Θ(n1.585)\Theta(n^{\log_2 3}) = \Theta(n^{1.585})
Strassen: 7T(n/2)+n27T(n/2) + n^21.751.75leavesΘ(nlog⁡27)=Θ(n2.807)\Theta(n^{\log_2 7}) = \Theta(n^{2.807})
2T(n/2)+n22T(n/2) + n^20.50.5rootΘ(n2)\Theta(n^2)

Trees also handle asymmetric branches. In T(n)=T(n/3)+T(2n/3)+nT(n) = T(n/3) + T(2n/3) + n, each complete level costs nn (sizes sum to nn), but depths differ: shortest log⁡3n\log_3 n, longest log⁡3/2n\log_{3/2} n. The first log⁡3n\log_3 n levels are complete and deeper ones not, so total is between roughly nlog⁡3nn\log_3 n and nlog⁡3/2nn\log_{3/2} n, i.e. Θ(nlog⁡n)\Theta(n\log n). The tree reasons with noninteger n/3n/3 and 2n/32n/3; rigorous bounds with actual floors use substitution. The master theorem and Akra–Bazzi generalization turn this into general rules including floors, ceilings and non-power terms, in divide and conquer.

Homogeneous linear recurrences

Hanoi, no-consecutive-ones strings and mergesort on powers of 2 share a new term linearly combining earlier ones with coefficients independent of nn, perhaps plus a constant. This family has a complete theory, also the theory of matrix powers.

The solution space

If (an)(a_n) and (an′)(a'_n) satisfy the recurrence, so does (λan+μan′)(\lambda a_n + \mu a'_n): solutions form vector subspace SS of sequence space. Mapping S→CkS \to \C^k to initial values (a0,…,ak−1)(a_0, \dots, a_{k-1}) is linear and bijective because initial values determine the sequence and any initial values extend. Thus dim⁡S=k\dim S = k: finding kk independent solutions describes all.

Try an=xna_n = x^n. Substitute and divide by xn−kx^{n-k} (if x≠0x \neq 0):

xk=c1xk−1+⋯+ck  ⟺  χ(x)=0.x^k = c_1 x^{k-1} + \cdots + c_k \iff \chi(x) = 0.

Every characteristic root gives a geometric solution. Since ck≠0c_k \neq 0, 0 is not a root. If the kk roots are distinct we have kk solutions; repeated roots need more, described next.

Proof

Use shift operator EE, (Ea)n=an+1(Ea)_n = a_{n+1}. Reindexed recurrence says an+k−c1an+k−1−⋯−ckan=0a_{n+k} - c_1 a_{n+k-1} - \cdots - c_k a_n = 0 for every n≥0n \ge 0, i.e. χ(E) a=0\chi(E)\,a = 0, and χ(E)=(E−r1)m1⋯(E−rs)ms\chi(E) = (E - r_1)^{m_1}\cdots(E - r_s)^{m_s} with commuting factors.

They are solutions. For polynomial qq, (E−r)(q(n) rn)=q(n+1)rn+1−r q(n)rn=(q(n+1)−q(n))rn+1(E - r)\big(q(n)\,r^n\big) = q(n+1)r^{n+1} - r\,q(n)r^n = \big(q(n+1) - q(n)\big)r^{n+1}, where q(n+1)−q(n)q(n+1) - q(n) has degree one less than qq (or zero for constant qq). Applying (E−ri)(E - r_i) mim_i times to njrinn^j r_i^n with j<mij < m_i gives 0, so χ(E)\chi(E) also annihilates it.

They are independent. Suppose ∑ipi(n) rin=0\sum_i p_i(n)\,r_i^n = 0 for all nn with some pi≠0p_i \neq 0, and choose such a relation with minimal D=∑pi≠0(deg⁡pi+1)D = \sum_{p_i \neq 0}(\deg p_i + 1). Choose index s′s' with ps′≠0p_{s'} \neq 0 and apply E−rs′E - r_{s'}. The rs′r_{s'} term becomes (ps′(n+1)−ps′(n))rs′n+1\big(p_{s'}(n+1) - p_{s'}(n)\big)r_{s'}^{n+1} of lower degree; each ri≠rs′r_i \neq r_{s'} term becomes (ri pi(n+1)−rs′ pi(n))rin\big(r_i\,p_i(n+1) - r_{s'}\,p_i(n)\big)r_i^n, a polynomial of the same degree as pip_i, with leading coefficient multiplied by ri−rs′≠0r_i - r_{s'} \neq 0. The new relation has measure below DD, so minimality makes all its polynomials zero. This forces pi=0p_i = 0 for every i≠s′i \neq s', leaving ps′(n) rs′n=0p_{s'}(n)\,r_{s'}^n = 0 for all nn; as rs′≠0r_{s'} \neq 0, ps′p_{s'} vanishes at infinitely many points and is zero. Contradiction.

They form a basis. There are kk independent solutions in a kk-dimensional space.

∎

Simple roots: Fibonacci and Binet’s formula

For Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}, χ(x)=x2−x−1\chi(x) = x^2 - x - 1, with roots φ=(1+5)/2≈1.618\varphi = (1 + \sqrt 5)/2 \approx 1.618 and ψ=(1−5)/2≈−0.618\psi = (1 - \sqrt 5)/2 \approx -0.618. General solution Fn=αφn+βψnF_n = \alpha\varphi^n + \beta\psi^n and initial values give F0=α+β=0F_0 = \alpha + \beta = 0 and F1=αφ+βψ=1F_1 = \alpha\varphi + \beta\psi = 1, so α=−β=1/(φ−ψ)=1/5\alpha = -\beta = 1/(\varphi - \psi) = 1/\sqrt 5. This is Binet’s formula:

Fn=φn−ψn5.F_n = \frac{\varphi^n - \psi^n}{\sqrt 5}.

That an expression with 5\sqrt 5 always yields integers is no miracle: irrational terms cancel upon binomial expansion. Since ∣ψ∣<1\abs{\psi} < 1, the second term has magnitude below 1/21/2 for all n≥0n \ge 0, so FnF_n is the nearest integer to φn/5\varphi^n/\sqrt 5. For no-consecutive-ones strings change initial conditions: bn=Fn+2b_n = F_{n+2}.

Repeated roots

If rr is a double root, the theorem gives rnr^n and n rnn\,r^n. For example an=6an−1−9an−2a_n = 6a_{n-1} - 9a_{n-2} with a0=1a_0 = 1, a1=6a_1 = 6 has χ(x)=(x−3)2\chi(x) = (x - 3)^2, so an=(α+βn)3na_n = (\alpha + \beta n)3^n. From a0=α=1a_0 = \alpha = 1 and a1=3(1+β)=6a_1 = 3(1 + \beta) = 6 we get β=1\beta = 1 and an=(n+1)3na_n = (n + 1)3^n. Check a2=6⋅6−9⋅1=27=3⋅32a_2 = 6\cdot 6 - 9\cdot 1 = 27 = 3\cdot 3^2.

Where does nn come from? If roots were rr and r+hr + h for small hh, sequence ((r+h)n−rn)/h\big((r + h)^n - r^n\big)/h would be a solution, tending as h→0h \to 0 to derivative n rn−1n\,r^{n-1}. When roots merge their geometric solutions become nearly equal, and the normalized difference survives as a new independent solution. Matrix form shows this too: a repeated root is a matrix that cannot be diagonalized.

Complex roots

With real coefficients nonreal roots occur in conjugate pairs r=ρeiθr = \rho e^{i\theta} and rˉ=ρe−iθ\bar r = \rho e^{-i\theta}. For a real sequence, coefficients of rnr^n and rˉn\bar r^n are conjugates, and their sum αrn+αˉrˉn=2Re⁡(αrn)\alpha r^n + \bar\alpha\bar r^n = 2\operatorname{Re}(\alpha r^n) rewrites using Euler’s formula as

ρn (Acos⁡(nθ)+Bsin⁡(nθ)),A,B∈R.\rho^n\,\big(A\cos(n\theta) + B\sin(n\theta)\big), \qquad A, B \in \R.

Magnitude ρ\rho determines growth and argument θ\theta oscillation. For an=2an−1−2an−2a_n = 2a_{n-1} - 2a_{n-2}, a0=a1=1a_0 = a_1 = 1, roots are 1±i=2 e±iπ/41 \pm i = \sqrt 2\,e^{\pm i\pi/4} and solution an=2n/2cos⁡(nπ/4)a_n = 2^{n/2}\cos(n\pi/4): period-8 oscillation with amplitude growing like 2 n\sqrt 2^{\,n}. For an=an−1−an−2a_n = a_{n-1} - a_{n-2} roots are e±iπ/3e^{\pm i\pi/3} of magnitude 1, and every initial sequence has period 6.

Long-term dominance

General form is a sum of terms pi(n) rinp_i(n)\,r_i^n, and the largest-magnitude root eventually wins.

Proof

Divide the general form by α1r1n\alpha_1 r_1^n: remaining terms are pi(n)(ri/r1)n/α1p_i(n)(r_i/r_1)^n/\alpha_1 with ∣ri/r1∣<1\abs{r_i/r_1} < 1, and a polynomial times a geometric term of magnitude ratio below 1 tends to 0. The second part is the same without division: ∣pi(n) rin∣→0\abs{p_i(n)\,r_i^n} \to 0 if ∣ri∣<1\abs{r_i} < 1.

∎

For order 2, an=c1an−1+c2an−2a_n = c_1 a_{n-1} + c_2 a_{n-2}, everything is visible in coefficient space. Parabola c12+4c2=0c_1^2 + 4c_2 = 0 separates real roots (above) from complex roots (below), with a double root on it. Both roots are inside the unit circle exactly in triangle ∣c2∣<1\abs{c_2} < 1, c1+c2<1c_1 + c_2 < 1, c2−c1<1c_2 - c_1 < 1: the stationarity region of an AR(2) process in statistics.

InteractiveCharacteristic roots and behavior
Parameters (c1,c2)(c_1, c_2)
complex rootsreal|r| < 1
Roots of x2−c1x−c2x^2 - c_1 x - c_2
The sequence a0,…,a24a_0, \dots, a_{24}
  • stability triangle: ∣r1∣,∣r2∣<1|r_1|, |r_2| < 1
  • parabola c12+4c2=0c_1^2 + 4c_2 = 0: double root
  • characteristic roots
  • sequence ana_n
  • dominant term
Coefficients
1
1
Initial values
1
1
an=an−1+an−2a_n = a_{n-1} + a_{n-2}
r1r_1, ∣r1∣|r_1|1.618, 1.618
r2r_2, ∣r2∣|r_2|−0.618, 0.618
a24a_{24}75 025
a24/a23a_{24}/a_{23} versus r1r_11.6180 vs 1.6180
an=0.724 (1.618)n+0.276 (−0.618)na_n = 0.724\,(1.618)^n + 0.276\,(-0.618)^n
The dominant root r1=1.618r_1 = 1.618 governs: an+1/an→r1a_{n+1}/a_n \to r_1.
Drag point (c1,c2)(c_1, c_2) in parameter space. Beside it are roots of x2−c1x−c2x^2 - c_1 x - c_2 with the unit circle (aqua) and dominant-magnitude circle ρ\rho (dashed). Below, the sequence and dashed dominant term or envelope. Try: (1) from Fibonacci, lower c2c_2 past the parabola and watch roots collide and leave the axis as a conjugate pair as oscillation begins; (2) enter the triangle and see the sequence decay from any start; (3) at a double root enable ‘divide by ρn\rho^n’: a line remains, factor α+βn\alpha + \beta n; (4) with c1=0c_1 = 0 both roots have equal magnitude and neither dominates.

Nonhomogeneous recurrences

Hanoi is not homogeneous: T(n)=2T(n−1)+1T(n) = 2T(n-1) + 1 has a term that does not depend on previous TT values. In general we consider

an=c1an−1+⋯+ckan−k+f(n),a_n = c_1 a_{n-1} + \cdots + c_k a_{n-k} + f(n),

where ff is a known function of nn. Solutions have the structure of any linear equation: if (pn)(p_n) is one solution, every other is pn+hnp_n + h_n with (hn)(h_n) a solution of the associated homogeneous recurrence, because the difference of two solutions satisfies the recurrence without ff. The solutions form an affine space of dimension kk.

For the ff encountered in practice, the particular solution is found by undetermined coefficients: propose a form with free coefficients and substitute.

Term f(n)f(n)Form of particular solution
polynomial of degree ddnm (A0+A1n+⋯+Adnd)n^m\,(A_0 + A_1 n + \cdots + A_d n^d)
q(n) snq(n)\,s^n, with qq a polynomial of degree ddnm (A0+A1n+⋯+Adnd) snn^m\,(A_0 + A_1 n + \cdots + A_d n^d)\,s^n

Here mm is the multiplicity of ss as a root of χ\chi (with s=1s = 1 in the first row), and m=0m = 0 if ss is not a root. The factor nmn^m is resonance: if the forcing term is already a homogeneous solution, proposing it as it stands gives 0=f(n)0 = f(n), so the degree must increase.

The rule is not a magic recipe. If f(n)=q(n)snf(n) = q(n)s^n with deg⁡q=d\deg q = d, the calculation in the previous proof shows that (E−s)d+1(E - s)^{d+1} annihilates ff. Applying (E−s)d+1(E - s)^{d+1} to the recurrence, aa satisfies the homogeneous recurrence with polynomial χ(x)(x−s)d+1\chi(x)(x - s)^{d+1}, in which ss has multiplicity m+d+1m + d + 1. By the previous theorem, ana_n is a combination of solutions of χ\chi plus terms njsnn^j s^n with j<m+d+1j < m + d + 1; those with j<mj < m already solve the original homogeneous recurrence, leaving exactly the form in the table.

The last case explains mergesort again. With n=2kn = 2^k and S(k)=T(2k)S(k) = T(2^k), the recurrence T(n)=2T(n/2)+nT(n) = 2T(n/2) + n becomes S(k)=2S(k−1)+2kS(k) = 2S(k-1) + 2^k: a change of variable turns divide and conquer into an order-1 linear recurrence with resonance. Its solution, S(k)=(S(0)+k)2kS(k) = (S(0) + k)2^k, is T(n)=nlog⁡2n+n T(1)T(n) = n\log_2 n + n\,T(1), and the log⁡n\log n of regime 2 in the tree is simply the resonance factor nmn^m.

Matrix form: the companion matrix

An order-kk recurrence must remember the last kk terms. Gather them in a state vector and each step is multiplication by a fixed matrix. For order 2:

[an+1an]=[c1c210][anan−1].\begin{bmatrix} a_{n+1} \\ a_n \end{bmatrix} = \begin{bmatrix} c_1 & c_2 \\ 1 & 0 \end{bmatrix}\begin{bmatrix} a_n \\ a_{n-1} \end{bmatrix}.

All the preceding theory can be read in C\mat{C} using what you know about eigenvectors.

  • Its eigenvalues are the characteristic roots. Expansion along the first row gives det⁡(xI−C)=χ(x)\det(x\mat{I} - \mat{C}) = \chi(x). More directly: if χ(r)=0\chi(r) = 0, the vector v=(rk−1,…,r,1)\vb{v} = (r^{k-1}, \dots, r, 1) satisfies Cv=rv\mat{C}\vb{v} = r\vb{v}, because the first component of Cv\mat{C}\vb{v} is c1rk−1+⋯+ck=rkc_1 r^{k-1} + \cdots + c_k = r^k and the rest are the shifted components of v\vb{v}. This is the geometric solution rnr^n seen as a state vector.
  • Simple roots are equivalent to diagonalizability. If the kk roots are distinct, the kk Vandermonde vectors vi\vb{v}_i are independent and C=VΛV−1\mat{C} = \mat{V}\mat{\Lambda}\mat{V}\inv. Then Cn=VΛnV−1\mat{C}^n = \mat{V}\mat{\Lambda}^n\mat{V}\inv, and the last component of Cnx0\mat{C}^n\vb{x}_0 is ∑iαirin\sum_i \alpha_i r_i^n: Binet’s formula is the diagonalization of C\mat{C}, and the constants αi\alpha_i are the coordinates of x0\vb{x}_0 in the eigenvector basis.
  • A repeated root is equivalent to non-diagonalizability. The last k−1k - 1 rows of C−rI\mat{C} - r\mat{I} are independent (each has a 1 in a different column), so its rank is at least k−1k - 1 and each eigenvalue has only one eigenvector. A root of multiplicity mm is then a Jordan block of size mm, and powers of a Jordan block produce n rn−1,(n2)rn−2,…n\,r^{n-1}, \binom{n}{2}r^{n-2}, \dots: the polynomial factors in the theorem (you will study these with the Jordan form).

For Fibonacci, Q=[1110]\mat{Q} = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix} and immediate induction gives

Qn=[Fn+1FnFnFn−1](n≥1).\mat{Q}^n = \begin{bmatrix} F_{n+1} & F_n \\ F_n & F_{n-1} \end{bmatrix} \qquad (n \ge 1).

Identities follow effortlessly. The determinant gives Cassini’s identity, Fn+1Fn−1−Fn2=det⁡Qn=(−1)nF_{n+1}F_{n-1} - F_n^2 = \det\mat{Q}^n = (-1)^n. And Q2n=(Qn)2\mat{Q}^{2n} = (\mat{Q}^n)^2 gives the doubling formulas F2n=Fn(2Fn+1−Fn)F_{2n} = F_n(2F_{n+1} - F_n) and F2n+1=Fn+12+Fn2F_{2n+1} = F_{n+1}^2 + F_n^2.

Distant terms in logarithmic time

The matrix form turns “compute ana_n” into “compute Cn\mat{C}^n”, and powers are computed with fast exponentiation from lesson 8: square repeatedly and multiply according to the bits of nn. At most this takes around 2log⁡2n2\log_2 n products of k×kk\times k matrices, each with O(k3)\bigO(k^3) arithmetic operations (naive matrix multiplication), versus O(kn)\bigO(kn) for the direct loop.

Two specialist nuances. First, for large integer terms, counting arithmetic operations is misleading: FnF_n has about nlog⁡2φ≈0.694 nn\log_2\varphi \approx 0.694\,n bits, and the real cost is dominated by the last multiplications of numbers that size. Even so, exponentiation beats the loop by far: its nn additions of increasingly long numbers cost Θ(n2)\Theta(n^2) bit operations; you will measure this in the implementation. Second, if only an mod ma_n \bmod m is needed (as in cryptography or counting problems with astronomical numbers), fast exponentiation works with bounded numbers and n=1018n = 10^{18}, which has 60 bits of which 24 are 1, takes about 60 squarings and 24 products: fewer than 90 matrix multiplications.

Implementation from scratch

First, the three models from the modelling section checked against brute force: we generate Hanoi moves, enumerate binary strings and count mergesort comparisons on an input constructed to be the worst possible.

[ ]Models versus brute forceBrowser
from functools import lru_cache
from itertools import product
import math
import numpy as np

def hanoi(n, origen="A", destino="C", aux="B"):
    """Genera los movimientos (disco, de, a) de la solución recursiva."""
    if n == 0:
        return
    yield from hanoi(n - 1, origen, aux, destino)
    yield (n, origen, destino)
    yield from hanoi(n - 1, aux, destino, origen)

print("Hanói, movimientos generados y 2^n - 1:")
print("  ", [(n, sum(1 for _ in hanoi(n)), 2**n - 1) for n in (1, 4, 8, 12)])

def sin_unos_seguidos(n):
    return sum(1 for s in product("01", repeat=n) if "11" not in "".join(s))

b = [1, 2]
for n in range(2, 13):
    b.append(b[n - 1] + b[n - 2])
print("\ncadenas sin '11', fuerza bruta:", [sin_unos_seguidos(n) for n in range(13)])
print("cadenas sin '11', recurrencia: ", b)

comparaciones = 0
def mergesort(xs):
    global comparaciones
    if len(xs) <= 1:
        return xs
    m = len(xs) // 2
    izq, der = mergesort(xs[:m]), mergesort(xs[m:])
    out, i, j = [], 0, 0
    while i < len(izq) and j < len(der):
        comparaciones += 1
        if izq[i] <= der[j]:
            out.append(izq[i]); i += 1
        else:
            out.append(der[j]); j += 1
    return out + izq[i:] + der[j:]

def peor_entrada(xs):
    """Reparte los elementos alternos entre las dos mitades: cada mezcla agota las dos listas a la vez."""
    if len(xs) <= 1:
        return xs
    return peor_entrada(xs[1::2]) + peor_entrada(xs[0::2])

@lru_cache(maxsize=None)
def W(n):
    """Recurrencia exacta del peor caso."""
    return 0 if n <= 1 else W((n + 1) // 2) + W(n // 2) + n - 1

rng = np.random.default_rng(0)
print("\n     n   W(n)  peor entrada  aleatoria  n·ceil(lg n) - 2^ceil(lg n) + 1   n lg n")
for n in [10, 100, 1000, 3000]:
    comparaciones = 0
    assert mergesort(peor_entrada(list(range(n)))) == list(range(n))
    c_peor = comparaciones
    comparaciones = 0
    mergesort(list(rng.permutation(n)))
    L = math.ceil(math.log2(n))
    print(f"{n:6d} {W(n):6d} {c_peor:11d} {comparaciones:10d} {n * L - 2**L + 1:20d} {n * math.log2(n):17.0f}")

The exact recurrence matches the actual count on the worst input and the closed formula with ceilings, and nlog⁡2nn\log_2 n is a good upper approximation. A random permutation needs only slightly fewer comparisons than the worst case: merging two random lists almost always exhausts one near the end.

Now the three solvers in the lab: direct (and memoized) evaluation, a closed form with numpy.roots roots plus a Vandermonde system for the constants, and powers of the companion matrix with exact integers.

[ ]Three solversBrowser
from functools import lru_cache
import numpy as np

def por_iteracion(coefs, iniciales, n):
    """a_n con un bucle: O(k n) operaciones."""
    k = len(coefs)
    a = list(iniciales)
    for m in range(k, n + 1):
        a.append(sum(c * a[m - 1 - i] for i, c in enumerate(coefs)))
    return a[n]

def memoizada(coefs, iniciales):
    """La recurrencia tal cual, con memoria: cada a_m se calcula una sola vez."""
    k = len(coefs)
    @lru_cache(maxsize=None)
    def a(n):
        if n < k:
            return iniciales[n]
        return sum(c * a(n - 1 - i) for i, c in enumerate(coefs))
    return a

def por_raices(coefs, iniciales):
    """Forma cerrada suponiendo raíces simples: a_n = sum_i alpha_i r_i^n."""
    k = len(coefs)
    r = np.roots([1.0] + [-c for c in coefs])        # raíces de x^k - c1 x^(k-1) - ... - ck
    V = np.vander(r, k, increasing=True).T            # V[n, i] = r_i^n para n = 0..k-1
    alpha = np.linalg.solve(V, np.array(iniciales, dtype=complex))
    return r, alpha, np.linalg.cond(V)

def matmul(A, B):
    return [[sum(A[i][t] * B[t][j] for t in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]

def matpow(M, e):
    """M^e por cuadrados repetidos, con los enteros exactos de Python."""
    R = [[int(i == j) for j in range(len(M))] for i in range(len(M))]
    while e:
        if e & 1:
            R = matmul(R, M)
        M = matmul(M, M)
        e >>= 1
    return R

def companera(coefs):
    k = len(coefs)
    return [list(coefs)] + [[int(j == i) for j in range(k)] for i in range(k - 1)]

def por_matriz(coefs, iniciales, n):
    """a_n es la última componente de C^n x_0, con x_0 = (a_(k-1), ..., a_0)."""
    k = len(coefs)
    P = matpow(companera(coefs), n)
    x0 = list(reversed(iniciales))
    return sum(P[k - 1][j] * x0[j] for j in range(k))

casos = {
    "Fibonacci": ([1, 1], [0, 1]),
    "tribonacci": ([1, 1, 1], [0, 0, 1]),
    "par complejo 1 ± i": ([2, -2], [1, 1]),
    "raíz doble 3": ([6, -9], [1, 6]),
}
for nombre, (c, ini) in casos.items():
    r, alpha, cond = por_raices(c, ini)
    print(f"{nombre}: raíces {np.round(r, 4)}, cond(V) = {cond:.1e}")
    for n in (12, 40):
        exacto = por_iteracion(c, ini, n)
        assert exacto == memoizada(c, ini)(n) == por_matriz(c, ini, n)
        cerrada = (alpha * r**n).sum()
        err = abs(cerrada - exacto) / max(1, abs(exacto))
        print(f"   n = {n}: exacto {exacto}, forma cerrada {cerrada.real:.10g}, error relativo {err:.1e}")

The three approaches agree where they should, with two lessons. The closed form with complex roots returns complex numbers whose imaginary part is rounding noise, even though the sequence is integer-valued. And with the double root, np.roots returns not 3 twice but a conjugate pair 3±3.7⋅10−8 i3 \pm 3.7\cdot 10^{-8}\,i, separated by about 10−710^{-7} (on the order of ε\sqrt{\varepsilon}, as expected for a double root): the Vandermonde matrix is nearly singular and the closed form loses half the digits. The “simple roots” solver does not know the correct answer is (n+1)3n(n + 1)3^n; the final code exercise asks you to fix it.

Binet’s formula is exact in mathematics and dangerous in floating point. With float64, φn\varphi^n has about 16 significant digits, and once FnF_n has more digits than can be represented, rounding to the nearest integer no longer suffices.

[ ]Floating-point Binet versus the exact matrixBrowser
import math, time

def fib_matriz(n):
    return matpow([[1, 1], [1, 0]], n)[0][1]

def fib_bucle(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

phi = (1 + math.sqrt(5)) / 2
def fib_binet(n):
    return round(phi**n / math.sqrt(5))

primero = next(n for n in range(200) if fib_binet(n) != fib_matriz(n))
print("primer n en que Binet con float64 falla:", primero)
for n in [primero, 100]:
    exacto, aprox = fib_matriz(n), fib_binet(n)
    print(f"  F_{n}: exacto {exacto}\n        Binet  {aprox}   error relativo {abs(aprox - exacto) / exacto:.1e}")
try:
    fib_binet(1500)
except OverflowError as e:
    print("Binet con n = 1500:", e)

print("\n     n    bits de F_n   bucle (s)   matriz (s)")
for n in [25_000, 50_000, 100_000]:
    t = time.perf_counter(); x = fib_bucle(n); t_bucle = time.perf_counter() - t
    t = time.perf_counter(); y = fib_matriz(n); t_matriz = time.perf_counter() - t
    assert x == y
    print(f"{n:7d} {x.bit_length():11d} {t_bucle:11.3f} {t_matriz:11.3f}")

Binet first fails at n=71n = 71, when F71≈3.1×1014F_{71} \approx 3.1\times 10^{14} still fits comfortably in a 64-bit integer: the problem is precision, not the size of the result. The relative error of 10−1610^{-16} with which φ\varphi is stored is multiplied by nn when raised to the nnth power (because (φ(1+δ))n≈φn(1+nδ)(\varphi(1 + \delta))^n \approx \varphi^n(1 + n\delta)), and about 3×10−153\times 10^{-15} relative error on 3×10143\times 10^{14} is already of order one. From n≈1475n \approx 1475, φn\varphi^n no longer even fits in a float64. The matrix with exact integers has neither problem. In time, whenever nn doubles the loop takes about four times as long (there are nn additions of increasingly long numbers, Θ(n2)\Theta(n^2) bit operations in total), and repeated squaring, already an order of magnitude faster at n=100 000n = 100\,000, grows more slowly: Python multiplies big integers with Karatsuba’s algorithm, the recurrence 3T(n/2)+n3T(n/2) + n from the tree figure in action, and its Θ(n1.585)\Theta(n^{1.585}) cost dominates.

Finally, the recursion tree in numbers: we evaluate T(n)=a T(n/b)+ncT(n) = a\,T(n/b) + n^c exactly on powers of bb and compare with the prediction for each regime. Also the unbalanced recurrence T(n)=T(⌊n/3⌋)+T(⌊2n/3⌋)+nT(n) = T(\lfloor n/3 \rfloor) + T(\lfloor 2n/3 \rfloor) + n, which the three-regime theorem does not cover.

[ ]The three regimes in numbersBrowser
import math
import numpy as np
import matplotlib.pyplot as plt

def T_dyv(a, b, c, L):
    """T(b^L) con T(1) = 1 y T(n) = a T(n/b) + n^c, evaluada desde abajo."""
    t = 1.0
    for j in range(1, L + 1):
        t = a * t + float(b**j) ** c
    return t

print("recurrencia            r      T(n)/predicción para n = 2^10, 2^15, 2^20")
for a, b, c, nombre in [(2, 2, 2, "2T(n/2) + n^2"), (2, 2, 1, "2T(n/2) + n"), (3, 2, 1, "3T(n/2) + n"), (7, 2, 2, "7T(n/2) + n^2")]:
    r = a / b**c
    def pred(n):
        if abs(r - 1) < 1e-12:
            return n**c * (math.log(n, b) + 1)
        return n**c if r < 1 else n ** math.log(a, b)
    cocientes = [T_dyv(a, b, c, L) / pred(b**L) for L in (10, 15, 20)]
    print(f"{nombre:18s} {r:6.3f}   " + "   ".join(f"{q:.4f}" for q in cocientes))

from functools import lru_cache
@lru_cache(maxsize=None)
def T_deseq(n):
    return 1 if n <= 2 else T_deseq(n // 3) + T_deseq(2 * n // 3) + n

ns = np.unique(np.logspace(1, 6, 60).astype(int))
cociente = [T_deseq(int(n)) / (n * math.log2(n)) for n in ns]
print("\nT(n/3) + T(2n/3) + n, cociente T(n) / (n log2 n) en n = 10^3, 10^4, 10^5, 10^6:",
      [round(T_deseq(10**e) / (10**e * math.log2(10**e)), 3) for e in (3, 4, 5, 6)])
print("cotas del árbol: 1/log2(3) =", round(1 / math.log2(3), 3), "  1/log2(3/2) =", round(1 / math.log2(1.5), 3))

plt.semilogx(ns, cociente, "o-", ms=3)
plt.axhline(1 / math.log2(3), color="gray", ls="--", label="rama más corta: 1/log2 3")
plt.axhline(1 / math.log2(1.5), color="gray", ls=":", label="rama más larga: 1/log2(3/2)")
plt.xlabel("n"); plt.ylabel("T(n) / (n log2 n)"); plt.legend(); plt.show()

In the root and leaf regimes, the ratio to the prediction stabilizes at a constant, the 1/(1−r)1/(1 - r) or r/(r−1)r/(r - 1) from the theorem; in the middle regime it is exactly 1 because the solution is nc(log⁡bn+1)n^c(\log_b n + 1). The unbalanced recurrence stays between the two tree bounds, as expected for Θ(nlog⁡n)\Theta(n\log n).

The library version

ToolWhat it doesBeware
sympy.rsolve(ecuación, a(n), iniciales)exact closed form of linear recurrences with constant coefficients (and some with polynomial coefficients)returns complex roots in exponential form, without converting to sines and cosines
sympy.fibonacci(n), sympy.lucas(n)exact terms
np.roots(coefs)roots of the characteristic polynomial (eigenvalues of its companion matrix)repeated roots appear separated by ε1/m\varepsilon^{1/m}
np.linalg.matrix_power(C, n)repeated squaringint64 integers overflow without warning
scipy.signal.lfilter(b, a, x)evaluates an=∑cian−i+entradana_n = \sum c_i a_{n-i} + \text{entrada}_n in C, very quicklyfloating point: inherits the instability of roots with modulus greater than 1
[ ]sympy.rsolve and the pitfalls of numerical librariesBrowser
import numpy as np
import sympy as sp
from scipy.signal import lfilter

n = sp.symbols("n", integer=True, nonnegative=True)
a = sp.Function("a")
problemas = {
    "Hanói": (a(n) - 2*a(n-1) - 1, {a(0): 0}),
    "resonancia": (a(n) - 2*a(n-1) - 2**n, {a(0): 1}),
    "raíz doble": (a(n) - 6*a(n-1) + 9*a(n-2), {a(0): 1, a(1): 6}),
    "par complejo": (a(n) - 2*a(n-1) + 2*a(n-2), {a(0): 1, a(1): 1}),
    "Fibonacci": (a(n) - a(n-1) - a(n-2), {a(0): 0, a(1): 1}),
}
for nombre, (ec, ini) in problemas.items():
    print(f"{nombre:13s} {sp.factor(sp.rsolve(ec, a(n), ini))}")

# la forma compleja es la oscilación real 2^(n/2) cos(n pi/4)
ec, ini = problemas["par complejo"]
sol = sp.rsolve(ec, a(n), ini)
print("¿igual a 2^(n/2) cos(n pi/4) en n = 0..15?",
      all(sp.simplify(sp.expand_complex(sol.subs(n, k)) - 2**sp.Rational(k, 2) * sp.cos(k * sp.pi / 4)) == 0 for k in range(16)))

# matrix_power con int64: F_93 ya no cabe en 64 bits con signo
Q = np.array([[1, 1], [1, 0]], dtype=np.int64)
for k in (92, 93):
    print(f"F_{k}: numpy int64 {np.linalg.matrix_power(Q, k)[0, 1]}   exacto {sp.fibonacci(k)}")
print("con dtype=object (enteros de Python):", np.linalg.matrix_power(Q.astype(object), 93)[0, 1])

# lfilter: a_n = a_(n-1) + a_(n-2) + x_n, con x = impulso en n = 1 -> Fibonacci en coma flotante
x = np.zeros(80); x[1] = 1.0
F_lfilter = lfilter([1.0], [1.0, -1.0, -1.0], x)
print("lfilter F_79:", int(F_lfilter[79]), "  exacto:", sp.fibonacci(79))

rsolve reproduces all the lesson’s closed forms, including resonance and the double root. Fibonacci’s appears with 5\sqrt 5 and the complex pair’s as ((1−i)n+(1+i)n)/2\big((1 - i)^n + (1 + i)^n\big)/2, the same real oscillation written with exponentials. Overflow in matrix_power deserves attention: F93≈1.2×1019F_{93} \approx 1.2\times 10^{19} exceeds 263−1≈9.2×10182^{63} - 1 \approx 9.2\times 10^{18} and NumPy returns a negative number without warning. lfilter is the fast way to evaluate linear recurrences in floating point (it is an IIR filter, the same object under another name), and therefore inherits the limits of float64: F79F_{79} is no longer exact.

Common mistakes

Exercises

NumericTen disks
How many moves does the optimal solution of the Towers of Hanoi with 10 disks need?
NumericStrings without consecutive ones
How many binary strings of length 10 contain no two consecutive ones?
NumericTiling a corridor
How many ways can a 2×102 \times 10 corridor be covered with 2×12 \times 1 dominoes (which can stand upright or lie horizontally)?
QuizA double root
What is the form of the general solution of an=4an−1−4an−2a_n = 4a_{n-1} - 4a_{n-2}?
QuizWhich level dominates?
What is the growth order of T(n)=4T(n/2)+n2T(n) = 4T(n/2) + n^2?
NumericStrassen's exponent
Strassen multiplies n×nn \times n matrices with 7 block products of size n/2n/2 and Θ(n2)\Theta(n^2) additions. If T(n)=Θ(nω)T(n) = \Theta(n^{\omega}), what is ω\omega? (Give three decimal places.)
NumericA periodic sequence
Let a0=1a_0 = 1, a1=2a_1 = 2 and an=an−1−an−2a_n = a_{n-1} - a_{n-2}. What is a100a_{100}?
NumericA resonant term
Let a0=0a_0 = 0 and an=3an−1+3na_n = 3a_{n-1} + 3^n for n≥1n \ge 1. What is a5a_5?
QuizChoosing the particular solution
What form should you propose for a particular solution of an=5an−1−6an−2+2na_n = 5a_{n-1} - 6a_{n-2} + 2^n?
ProofA bound with floors
Prove: Let T(1)=1T(1) = 1 and T(n)=2T(⌊n/2⌋)+nT(n) = 2T(\lfloor n/2 \rfloor) + n for n≥2n \ge 2. There is a constant cc such that T(n)≤c nlog⁡2nT(n) \le c\,n\log_2 n for all n≥2n \ge 2.
0
We will prove this by strong induction using substitution, choosing cc and the base cases carefully.

Step 1 of 4. Why can induction not start at n=1n = 1?

ProofSolve and prove
Prove: If a0=1a_0 = 1 and an=2an−1+3a_n = 2a_{n-1} + 3 for n≥1n \ge 1, then an=2n+2−3a_n = 2^{n+2} - 3 for all n≥0n \ge 0.
0
First obtain the formula using nonhomogeneous theory; then prove it by induction, which turns it into a theorem.

Step 1 of 3. What particular solution should we propose?

CodeA solver with multiplicities
Implement solve_linear_recurrence(coefs, iniciales) for an=c1an−1+⋯+ckan−ka_n = c_1 a_{n-1} + \cdots + c_k a_{n-k}, with coefs = [c1, ..., ck] and iniciales = [a0, ..., a(k-1)]. Return a list of tuples (r, m, [alpha_0, ..., alpha_(m-1)]), one per distinct root rr of multiplicity mm, such that an=∑r(α0+α1n+⋯+αm−1nm−1) rna_n = \sum_r (\alpha_0 + \alpha_1 n + \cdots + \alpha_{m-1} n^{m-1})\,r^n. The starter code assumes simple roots and fails with repeated roots: group roots that np.roots returns separated by rounding and solve the confluent Vandermonde system, whose columns are njrnn^j r^n. The tests compare your closed form with direct evaluation.
import numpy as np

def solve_linear_recurrence(coefs, iniciales):
  """Devuelve [(r, m, [alpha_0, ..., alpha_(m-1)]), ...]."""
  k = len(coefs)
  r = np.roots([1.0] + [-c for c in coefs])
  # versión ingenua: supone que todas las raíces son simples
  V = np.vander(r, k, increasing=True).T          # V[n, i] = r_i^n
  alpha = np.linalg.solve(V, np.array(iniciales, dtype=complex))
  return [(r[i], 1, [alpha[i]]) for i in range(k)]
Shift+Enter to run

Summary

Key idea
A recurrence is an algorithm or decomposition written as an equation; solving it means finding the function that satisfies it, and the proof is always induction. For linear recurrences with constant coefficients, the roots of the characteristic polynomial, which are the eigenvalues of the companion matrix, decide everything.
  • Modelling requires a bijective decomposition (in counting) or a faithful analysis of the code (in algorithms), and the correct initial values: Hanoi gives T(n)=2T(n−1)+1T(n) = 2T(n-1) + 1, strings without 1111 give Fibonacci and mergesort gives W(n)=W(⌈n/2⌉)+W(⌊n/2⌋)+n−1W(n) = W(\lceil n/2 \rceil) + W(\lfloor n/2 \rfloor) + n - 1.
  • Unrolling suggests the solution; the substitution method proves it by induction with explicit constants. If the step fails because of a lower-order term, strengthen the hypothesis by subtracting it. Floors and ceilings are handled in the induction or with monotonicity.
  • Recursion trees: in T(n)=aT(n/b)+ncT(n) = aT(n/b) + n^c the cost per level is ncrjn^c r^j with r=a/bcr = a/b^c. If r<1r < 1 the root dominates, Θ(nc)\Theta(n^c); if r=1r = 1, all levels do, Θ(nclog⁡n)\Theta(n^c\log n); if r>1r > 1, the leaves dominate, Θ(nlog⁡ba)\Theta(n^{\log_b a}).
  • Homogeneous linear recurrences: the general solution is ∑ipi(n) rin\sum_i p_i(n)\,r_i^n with deg⁡pi\deg p_i less than the multiplicity of rir_i. Complex roots ρe±iθ\rho e^{\pm i\theta} give ρn(Acos⁡nθ+Bsin⁡nθ)\rho^n(A\cos n\theta + B\sin n\theta), and in the long run the root of greatest modulus dominates.
  • Nonhomogeneous: particular plus homogeneous, with the particular solution found by undetermined coefficients and a factor nmn^m for resonance. Constants are fitted at the end, on the sum.
  • Matrix form: xn+1=Cxn\vb{x}_{n+1} = \mat{C}\vb{x}_n with the companion matrix, whose eigenvalues are the characteristic roots. Binet is its diagonalization, repeated roots are Jordan blocks, and Cn\mat{C}^n by squaring gives distant terms in O(k3log⁡n)\bigO(k^3\log n) operations, exact with integers, unlike floating-point Binet.