Given and the first terms, compute for astronomically large .

The unifying view

All fast methods compute the same object:

the characteristic polynomial. If , then

They differ only in how the polynomial multiplication modulo is performed.

MethodMultiplicationTime
Matrix exponentiationmatrices
Kitamasaschoolbook polynomials
Bostan-MoriNTT

For , : matrices are operations, Kitamasa , Bostan-Mori .

Bostan-Mori — the fastest

The generating function of a linear recurrence is rational: with . To extract :

and is a polynomial in . So writing and splitting into even and odd parts :

Each step halves and costs two polynomial multiplications.

long long bostanMori(Poly P, Poly Q, long long n, long long MOD) {
    while (n) {
        Poly Qneg = Q;
        for (size_t i = 1; i < Qneg.size(); i += 2) Qneg[i] = (MOD - Qneg[i]) % MOD;
        Poly U = mul(P, Qneg), V = mul(Q, Qneg);
        P.assign((U.size() + 1 - (n & 1)) / 2, 0);
        for (size_t i = (n & 1); i < U.size(); i += 2) P[i / 2] = U[i];
        Q.assign((V.size() + 1) / 2, 0);
        for (size_t i = 0; i < V.size(); i += 2) Q[i / 2] = V[i];
        n >>= 1;
    }
    return P.empty() ? 0 : P[0] * powmod(Q[0], MOD - 2, MOD) % MOD;
}

with NTT, with schoolbook (still competitive with Kitamasa and shorter to write).

Finding the recurrence: Berlekamp-Massey

Often you can compute the first few terms but do not know the recurrence. Berlekamp-Massey recovers the shortest linear recurrence from terms in .

The combination is the technique: brute-force ~200 terms, run Berlekamp-Massey, then Bostan-Mori to reach .

This works surprisingly often, because these sequences satisfy linear recurrences:

  • counts of walks in a fixed graph,
  • tilings of a board,
  • any DP with a fixed finite state set and constant transitions,
  • determinants of banded matrices,
  • many combinatorial counting sequences.

You do not need to understand the recurrence — just verify it predicts terms beyond those it was fitted to.

vector<long long> rec = berlekampMassey(first200Terms);
long long ans = kitamasa(first200Terms, rec, n);

From a matrix to a recurrence

If the DP is with a matrix, its characteristic polynomial (degree ) gives a linear recurrence for every entry of by Cayley-Hamilton. Compute it with Faddeev-LeVerrier () or the Hessenberg method (), then use Kitamasa — reducing to .

For sparse , Wiedemann finds the minimal polynomial in .

Non-homogeneous terms

:

Fix
constant extend the state with a permanent 1
polynomial of degree extend with and encode the binomial updates
extend with (multiplied by each step)
extend with all products

The recurrence order grows, but the method is unchanged.

Prefix sums

also satisfies a linear recurrence of order — add to the state with . So “sum the first terms” is the same problem.

See also: Bostan-Mori · Berlekamp-Massey · Linear Recurrences