Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Linear Recurrences & Matrix Powers

Characteristic roots, Fibonacci in closed form, and the n-th term in O(log n) steps.

F1018F_{10^{18}} has about 2×10172\times10^{17} decimal digits, yet its last digit is easy to find: it is 5. Linear recurrences have closed forms built from the roots of a polynomial, generating functions that are ratios of polynomials, and an nn-th term that takes O(log⁡n)O(\log n) arithmetic operations. And one innocent question about them, whether a term is ever zero, is still open.

What you’ll learn

  • Solve a linear recurrence with constant coefficients from the roots of its characteristic polynomial, including repeated roots and a constant non-homogeneous term.
  • Derive the generating function of a linear recurrence and recover Binet's formula by partial fractions.
  • Compute the nn-th term with O(k3log⁡n)O(k^3\log n) operations by matrix powers, Fibonacci numbers by fast doubling, and terms modulo mm for huge nn.
  • Use the Kitamasa–Fiduccia method and Berlekamp–Massey, and state what is known about the Skolem problem.

Characteristic roots

DerivationProof sketch
  1. rn−c1rn−1−⋯−ckrn−k = r n−k χ(r)r^n-c_1r^{n-1}-\dots-c_kr^{n-k}\ =\ r^{\,n-k}\,\chi(r)

    Roots give solutions. Substituting an=rna_n=r^n and dividing by rn−kr^{n-k} shows that rnr^n is a solution exactly when χ(r)=0\chi(r)=0:

  2. (xddx)j[xn−c1xn−1−⋯−ckxn−k]x=r=njrn−c1(n−1)jrn−1−⋯=0\Big(x\frac{d}{dx}\Big)^{j}\Big[x^{n}-c_1x^{n-1}-\dots-c_kx^{n-k}\Big]_{x=r}=n^jr^n-c_1(n-1)^jr^{n-1}-\dots=0

    Repeated roots. If rr is a root of multiplicity mm, it is also a root of the first m−1m-1 derivatives of xn−kχ(x)x^{n-k}\chi(x). Applying the operator x ddxx\,\frac{d}{dx} up to m−1m-1 times and setting x=rx=r shows that njrnn^jr^n is a solution for each j<mj<m:

  3. an=∑i=1s(αi,0+αi,1n+⋯+αi,mi−1nmi−1) ri na_n=\sum_{i=1}^{s}\big(\alpha_{i,0}+\alpha_{i,1}n+\dots+\alpha_{i,m_i-1}n^{m_i-1}\big)\,r_i^{\,n}

    A basis. These m1+⋯+ms=km_1+\dots+m_s=k sequences are linearly independent (a generalized Vandermonde argument), and the solution space has dimension kk, so they span it.

For the Fibonacci numbers, χ(x)=x2−x−1\chi(x)=x^2-x-1 has roots φ=(1+5)/2\varphi=(1+\sqrt5)/2, the golden ratio, and ψ=(1−5)/2≈−0.618\psi=(1-\sqrt5)/2\approx-0.618. Fitting F0=0F_0=0, F1=1F_1=1 gives Binet's formula

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

Since ∣ψn/5∣<1/2\abs{\psi^n/\sqrt5}<1/2 for all n≥0n\ge0, FnF_n is the integer nearest to φn/5\varphi^n/\sqrt5. That is exact mathematics but poor computing: in 64-bit floating point, rounding φn/5\varphi^n/\sqrt5 first gives a wrong answer at n=71n=71.

A repeated root brings a polynomial factor: an=4an−1−4an−2a_n=4a_{n-1}-4a_{n-2} has χ(x)=(x−2)2\chi(x)=(x-2)^2, so an=(A+Bn) 2na_n=(A+Bn)\,2^n, and a0=1a_0=1, a1=4a_1=4 give an=(n+1) 2na_n=(n+1)\,2^n. A constant inhomogeneous term needs one particular solution: an=2an−1+1a_n=2a_{n-1}+1 is solved by the constant −1-1, so an=A 2n−1a_n=A\,2^n-1, and the Tower of Hanoi's a0=0a_0=0 gives 2n−12^n-1.

Think first The sequence an=5an−1−6an−2a_n=5a_{n-1}-6a_{n-2} starts with a0=0a_0=0, a1=1a_1=1. Use the roots of x2−5x+6x^2-5x+6 to find a closed form, and then a5a_5.

The roots are 2 and 3, so an=A 3n+B 2na_n=A\,3^n+B\,2^n; the initial values give A=1A=1, B=−1B=-1, so an=3n−2na_n=3^n-2^n and a5=243−32=211a_5=243-32=211. The terms run 0,1,5,19,65,2110, 1, 5, 19, 65, 211, and the larger root, 3, controls the growth.

Generating functions

A generating function packs a sequence into a power series, A(x)=∑n≥0anxnA(x)=\sum_{n\ge0}a_nx^n, and turns the recurrence into algebra. For Fibonacci, multiply the recurrence by xnx^n and sum over n≥2n\ge2:

DerivationThe Fibonacci generating function, and Binet again
  1. F(x)−xF(x)−x2F(x) = F0+(F1−F0) x = x⟹F(x)=x1−x−x2F(x)-xF(x)-x^2F(x)\ =\ F_0+(F_1-F_0)\,x\ =\ x\qquad\Longrightarrow\qquad F(x)=\frac{x}{1-x-x^2}

    Every shifted series lines up with the original, and only the first terms are left over:

  2. x(1−φx)(1−ψx) = 15(11−φx−11−ψx)\frac{x}{(1-\varphi x)(1-\psi x)}\ =\ \frac{1}{\sqrt5}\Big(\frac{1}{1-\varphi x}-\frac{1}{1-\psi x}\Big)

    The denominator factors with the reciprocals of the characteristic roots, because φ+ψ=1\varphi+\psi=1 and φψ=−1\varphi\psi=-1; split into partial fractions, using φ−ψ=5\varphi-\psi=\sqrt5:

  3. F(x)=15∑n≥0(φn−ψn)xnF(x)=\frac{1}{\sqrt5}\sum_{n\ge0}\big(\varphi^n-\psi^n\big)x^n

    Each fraction is a geometric series, and reading off the coefficient of xnx^n gives Binet's formula:

Proof. Multiply: Q(x)A(x)=∑n(an−c1an−1−⋯−ckan−k)xnQ(x)A(x)=\sum_n\big(a_n-c_1a_{n-1}-\dots-c_ka_{n-k}\big)x^n, with aj=0a_j=0 for j<0j<0. The coefficient of xnx^n vanishes for every n≥kn\ge k exactly when the recurrence holds, so Q(x)A(x)Q(x)A(x) is a polynomial of degree less than kk. The same bookkeeping turns sums, shifts and convolutions of sequences into products of rational functions, which is why generating functions dominate the analysis of counting problems.

The n-th term in O(log n) operations

Stack kk consecutive terms into a state vector sn=(an+k−1,…,an+1,an)Ts_n=(a_{n+k-1},\dots,a_{n+1},a_n)^{\mathsf T}. One step of the recurrence is a multiplication by the companion matrix, whose first row is (c1,…,ck)(c_1,\dots,c_k) and whose other rows shift the vector down: sn+1=Msns_{n+1}=Ms_n, so sn=Mns0s_n=M^ns_0. Computing MnM^n by repeated squaring takes O(log⁡n)O(\log n) matrix products, each O(k3)O(k^3) with the schoolbook method: matrix exponentiation finds ana_n in O(k3log⁡n)O(k^3\log n) arithmetic operations. For Fibonacci:

(1110)n=(Fn+1FnFnFn−1).\begin{pmatrix}1&1\\1&0\end{pmatrix}^{n}=\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}.
DerivationFast doubling, from squaring the matrix
  1. F2m=Fm+1Fm+FmFm−1=Fm (2Fm+1−Fm)F_{2m}=F_{m+1}F_m+F_mF_{m-1}=F_m\,\big(2F_{m+1}-F_m\big)

    Square MmM^m to get M2mM^{2m} and compare the top-right entries, using Fm−1=Fm+1−FmF_{m-1}=F_{m+1}-F_m:

  2. F2m+1=Fm+12+Fm2F_{2m+1}=F_{m+1}^2+F_m^2

    The top-left entries give the odd index:

  3. (Fm, Fm+1) ⟼ {(F2m, F2m+1)next bit 0(F2m+1, F2m+F2m+1)next bit 1(F_m,\,F_{m+1})\ \longmapsto\ \begin{cases}(F_{2m},\,F_{2m+1}) & \text{next bit }0\\ (F_{2m+1},\,F_{2m}+F_{2m+1}) & \text{next bit }1\end{cases}

    So the pair (Fm,Fm+1)(F_m,F_{m+1}) yields (F2m,F2m+1)(F_{2m},F_{2m+1}) with three multiplications, and one addition advances to (F2m+1,F2m+2)(F_{2m+1},F_{2m+2}) when the next bit of nn is 1. That is O(log⁡n)O(\log n) multiplications, with no matrices at all:

python
def fib_pair(n, m):
    """Return (F(n) mod m, F(n+1) mod m)."""
    if n == 0:
        return (0, 1 % m)
    a, b = fib_pair(n // 2, m)            # a = F(k), b = F(k+1), k = n // 2
    c = a * ((2 * b - a) % m) % m          # F(2k)   = F(k) * (2F(k+1) - F(k))
    d = (a * a + b * b) % m                # F(2k+1) = F(k)^2 + F(k+1)^2
    return (d, (c + d) % m) if n % 2 else (c, d)

print(fib_pair(10**18, 10)[0])             # 5
print(fib_pair(10**18, 10**9 + 7)[0])      # 209783453

The recursion is only about log⁡2n≈60\log_2 n\approx60 calls deep for n=1018n=10^{18}. Reducing modulo mm at every step keeps the numbers small.

Modulo mm, the pairs (Fn mod m, Fn+1 mod m)(F_n\bmod m,\,F_{n+1}\bmod m) take at most m2m^2 values, and each pair determines its predecessor as well as its successor, so the sequence is purely periodic. Its period is the Pisano period π(m)\pi(m): π(10)=60\pi(10)=60, π(100)=300\pi(100)=300, π(1000)=1500\pi(1000)=1500, and in general π(m)≤6m\pi(m)\le6m, with equality exactly when m=2⋅5km=2\cdot5^k for some k≥1k\ge1.

Predict before you look

Use π(10)=60\pi(10)=60, the fact that 101810^{18} leaves remainder 40 when divided by 60, and F40=102,334,155F_{40}=102{,}334{,}155. What is the last digit of F1018F_{10^{18}}?

Show the answer

5

The last digits repeat every 60 terms, so the last digit of F1018F_{10^{18}} is that of F40F_{40}, which is 5. fib_pair(10**18, 10) agrees. For a modulus whose period you do not know, fast doubling needs no period at all.

Large k: polynomials instead of matrices

For an order-kk recurrence with kk in the hundreds, k3k^3 per matrix product hurts. By the Cayley–Hamilton theorem the companion matrix satisfies χ(M)=0\chi(M)=0, so MnM^n depends only on xnx^n modulo χ\chi. This gives the method contest programmers call Kitamasa's, and that Fiduccia (1985) analyzed with fast polynomial arithmetic:

DerivationThe n-th term from x^n mod χ(x)
  1. an=(Ena)0=(R(E) a)0=∑j=0k−1rj aj,R(x)=∑j<krjxj=xn mod χ(x)a_n=\big(E^na\big)_0=\big(R(E)\,a\big)_0=\sum_{j=0}^{k-1}r_j\,a_j,\qquad R(x)=\sum_{j<k}r_jx^j=x^n\bmod\chi(x)

    Divide xnx^n by χ\chi: xn=q(x)χ(x)+R(x)x^n=q(x)\chi(x)+R(x) with deg⁡R<k\deg R<k. The shift operator EE, which maps (at)(a_t) to (at+1)(a_{t+1}), satisfies χ(E)a=0\chi(E)a=0, so the quotient part vanishes:

  2. O(k2log⁡n) schoolbookO(klog⁡k log⁡n) with FFT multiplicationO(k^2\log n)\ \text{schoolbook}\qquad O(k\log k\,\log n)\ \text{with FFT multiplication}

    Compute xn mod χx^n\bmod\chi by repeated squaring of polynomials, reducing after each product. Each step multiplies two polynomials of degree below kk:

Where does the recurrence come from? Often you only have numbers. The Berlekamp–Massey algorithm (Berlekamp, 1968; Massey, 1969, who recast it as finding the shortest linear feedback shift register) takes NN terms of a sequence over a field and returns the shortest linear recurrence that generates them, in O(N2)O(N^2) operations. A recurrence of order kk is determined by 2k2k consecutive terms.

That gives a standard contest pipeline for "count the objects of size nn, modulo a prime, for nn up to 101810^{18}": compute the first few hundred answers with a slow dynamic program, let Berlekamp–Massey find a recurrence, check it on extra terms, then evaluate the nn-th term with Kitamasa's method. It works whenever the answers satisfy a linear recurrence, which is the case for counts that a finite automaton or a fixed-width transfer matrix generates.

Check your understanding

You suspect that a sequence modulo a prime satisfies a linear recurrence of order at most 50. How many consecutive terms must Berlekamp–Massey see to be sure of finding it?

  1. 50
  2. 51
  3. 100
  4. 2500
Show the answer

C. 100

2k=1002k=100 terms suffice for order at most k=50k=50: if two sequences each satisfy a recurrence of order at most 50 and agree on their first 100 terms, their difference satisfies a recurrence of order at most 100 and starts with 100 zeros, so it is zero everywhere. With fewer terms, a shorter but wrong recurrence can fit the data. In practice, feed it more terms and verify the result on extra ones.

Does it ever hit zero? The Skolem problem

The progressions are easy to see in examples: an=an−2a_n=a_{n-2} with a0=0a_0=0, a1=1a_1=1 vanishes at every even nn. They can be found effectively. The trouble is the finite exceptional set: the proof uses pp-adic analysis and gives no bound on how large an isolated zero can be. Whence the decision question.

Think first Why can't we decide the Skolem problem by computing terms until a zero appears?

That search finds a zero if there is one, so it semi-decides the "yes" answer. But if no zero exists it runs forever, and Skolem–Mahler–Lech gives no bound telling it when to stop: for that we would need an effective bound on the largest isolated zero. Decidability up to order 4 comes from exactly such bounds, proved with deep results on linear forms in logarithms.

Key takeaways

  • An order-kk linear recurrence is solved by ∑iPi(n)ri n\sum_iP_i(n)r_i^{\,n} over the roots rir_i of its characteristic polynomial, with deg⁡Pi\deg P_i below the multiplicity of rir_i.
  • Its generating function is P(x)/Q(x)P(x)/Q(x) with Q(x)=xkχ(1/x)Q(x)=x^k\chi(1/x), and partial fractions give the closed form, as in F(x)=x/(1−x−x2)F(x)=x/(1-x-x^2) and Binet's formula.
  • The nn-th term takes O(k3log⁡n)O(k^3\log n) operations by companion-matrix powers and O(k2log⁡n)O(k^2\log n) by computing xn mod χ(x)x^n\bmod\chi(x); Fibonacci numbers need only fast doubling. Modulo mm the sequence is periodic, with period at most 6m6m for Fibonacci.
  • Berlekamp–Massey recovers a recurrence of order kk from 2k2k terms. Whether a given recurrence ever hits zero (the Skolem problem) is decidable only up to order 4.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A recurrence has characteristic polynomial (x−3)2(x+1)(x-3)^2(x+1). What is the form of its general solution?

  1. A 3n+B 3n+C(−1)nA\,3^n+B\,3^n+C(-1)^n
  2. A 3n+C(−1)nA\,3^n+C(-1)^n
  3. (A+Bn) 3n+C(−1)n(A+Bn)\,3^n+C(-1)^n
  4. (A+Bn2) 3n+C(−1)n(A+Bn^2)\,3^n+C(-1)^n
Show the answer

C. (A+Bn) 3n+C(−1)n(A+Bn)\,3^n+C(-1)^n

A root of multiplicity 2 contributes 3n3^n and n 3nn\,3^n, and the simple root −1-1 contributes (−1)n(-1)^n: three independent solutions for an order-3 recurrence, matching its three initial values.

Question 2

You need the 101810^{18}-th term, modulo a prime, of a recurrence of order k=300k=300. Which method has the best arithmetic cost?

  1. Iterate the recurrence 101810^{18} times
  2. Raise the 300×300300\times300 companion matrix to the power 101810^{18}
  3. Evaluate Binet's formula in floating point
  4. Compute x1018 mod χ(x)x^{10^{18}}\bmod\chi(x) by repeated squaring of polynomials
Show the answer

D. Compute x1018 mod χ(x)x^{10^{18}}\bmod\chi(x) by repeated squaring of polynomials

Kitamasa's method costs O(k2log⁡n)≈9×104⋅60≈5×106O(k^2\log n)\approx9\times10^4\cdot60\approx5\times10^6 multiplications with schoolbook polynomial products, against O(k3log⁡n)≈1.6×109O(k^3\log n)\approx1.6\times10^9 for the matrix power. Iterating needs knkn operations, and floating point cannot work modulo a prime at all.

Question 3

Why is the Fibonacci sequence modulo mm purely periodic, that is, periodic from its very first term?

  1. Because there are at most m2m^2 pairs of consecutive residues, and each pair determines both the next pair and the previous one
  2. Because FnF_n grows like φn\varphi^n
  3. Because mm must be prime
  4. Because Binet's formula is periodic
Show the answer

A. Because there are at most m2m^2 pairs of consecutive residues, and each pair determines both the next pair and the previous one

Some pair must repeat among the first m2+1m^2+1, and since the map from a pair to the next is invertible (Fn−1=Fn+1−FnF_{n-1}=F_{n+1}-F_n), the first repeated pair is (0,1)(0,1) itself. Hence π(m)≤m2\pi(m)\le m^2; the sharper bound π(m)≤6m\pi(m)\le6m needs number theory.

Question 4

What is known about deciding whether an integer linear recurrence ever has a zero term?

  1. It is undecidable, by a reduction from the halting problem
  2. It is decidable up to order 4 and open from order 5
  3. It is decidable for every order, by the Skolem–Mahler–Lech theorem
  4. It is decidable only for order 2
Show the answer

B. It is decidable up to order 4 and open from order 5

Skolem–Mahler–Lech says the zeros form a finite set plus finitely many arithmetic progressions, but its proof gives no bound on the finite set. Effective bounds from linear forms in logarithms settle orders up to 4; order 5 and beyond remain open, with conditional algorithms for simple recurrences.

Further reading

  • R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994), chapters 6 and 7.
  • C. M. Fiduccia, "An efficient formula for linear recurrences," SIAM Journal on Computing 14(1) (1985), 106–112.
  • J. L. Massey, "Shift-register synthesis and BCH decoding," IEEE Transactions on Information Theory 15(1) (1969), 122–127.
  • G. Everest, A. van der Poorten, I. Shparlinski & T. Ward, Recurrence Sequences (American Mathematical Society, 2003).