Learn the pattern · ~15 min
Matrix Exponentiation
also called linear recurrence by matrix power
If each step applies the same linear rule to a small state, write the rule as a matrix M: then n steps is Mⁿ, and fast power gets it in about log₂ n matrix multiplications.
Reach for it when you read
- +A recurrence like
dp[i] = dp[i−1] + dp[i−2](a fixed number of earlier terms) but n is up to 10¹⁸. - +"Answer mod 10⁹ + 7" for a count that grows step by step with the same rule every step.
- +Count walks of exactly k steps on a small graph (a keypad, a few states), with k huge.
- +A small state (k ≤ about 100) and a huge number of steps: k³ log n fits, n does not.
Not this one when
- ×n ≤ about 10⁷: a plain 1-D DP loop is simpler and fast enough.
- ×The rule changes from step to step, or depends on i itself: the matrix isn't fixed, so plain DP.
- ×A single number to a huge power: fast power on numbers (math), no matrix needed.
Learn Matrix Exponentiation
First, what's a matrix, and what does "exponentiation" mean?
A matrix is a grid of numbers. A 2 × 2 matrix has two rows and two columns, like [[1, 2], [3, 4]] (row 0 is 1 2, row 1 is 3 4).
To multiply two matrices, entry (i, j) of the result is row i of the first times column j of the second: multiply the pairs and add them up.
[1 2] [5 6] [1·5 + 2·7 1·6 + 2·8] [19 22]
[3 4] · [7 8] = [3·5 + 4·7 3·6 + 4·8] = [43 50]Exponentiation is raising to a power: M³ = M · M · M. Matrix exponentiation finds the n-th term of a recurrence like Fibonacci in about log₂ n steps, even for n = 10¹⁸. The idea: write one step of the recurrence as a matrix M. Then n steps are Mⁿ, and Mⁿ can be built by squaring.
Fibonacci as a 2 × 2 matrix
Fibonacci is F(0) = 0, F(1) = 1, and each term is the sum of the two before: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233.
One step takes the pair (F(i), F(i − 1)) to the next pair (F(i + 1), F(i)). Write that as a multiplication:
[F(i+1)] [1 1] [F(i) ] row 0: new cur = 1·cur + 1·prev
[F(i) ] = [1 0] [F(i-1)] row 1: new prev = 1·cur + 0·prevSo M = [[1, 1], [1, 0]] is one Fibonacci step, and applying it n times is Mⁿ. Multiply it out and you find Mⁿ = [[F(n+1), F(n)], [F(n), F(n−1)]]: the Fibonacci numbers sit right inside the matrix.
The trick is that you don't need to multiply by M one step at a time. Square it, and the exponent doubles:
| power | what happens | matrix |
|---|---|---|
| M¹ | one step | [[1, 1], [1, 0]] |
| M² | M¹ · M¹: row 0 is 1·1 + 1·1 = 2 and 1·1 + 1·0 = 1 | [[2, 1], [1, 1]] |
| M⁴ | M² · M²: two steps, twice | [[5, 3], [3, 2]] |
| M⁸ | M⁴ · M⁴ | [[34, 21], [21, 13]] |
M⁸ holds F(9) = 34, F(8) = 21 and F(7) = 13, after only 3 multiplications instead of 7.
The code for it
typedef vector<vector<long long>> Mat;
const long long MOD = 1000000007;
Mat mul(const Mat& A, const Mat& B) {
int k = A.size();
Mat C(k, vector<long long>(k, 0));
for (int i = 0; i < k; i++)
for (int t = 0; t < k; t++)
for (int j = 0; j < k; j++)
C[i][j] = (C[i][j] + A[i][t] * B[t][j]) % MOD; // row i of A times column j of B
return C;
}
Mat power(Mat base, long long n) {
int k = base.size();
Mat result(k, vector<long long>(k, 0));
for (int i = 0; i < k; i++) result[i][i] = 1; // identity = M⁰
while (n > 0) {
if (n & 1) result = mul(result, base); // this bit of n is on
base = mul(base, base); // M, M², M⁴, M⁸, …
n >>= 1;
}
return result;
}You don't need to memorise this. mul is the row-times-column rule from the top. power is the squaring table: base runs through M, M², M⁴, M⁸, …, and whenever a bit of n is on, that power is multiplied into result.
Why does result start at the identity [[1, 0], [0, 1]] and not at M? Because the identity is M⁰: multiplying by it changes nothing, like starting a product at 1. Start at M and every answer is one step too far.
Fine, but how does this help us?
Here's the classic problem: Climbing Stairs. You climb a staircase taking 1 or 2 stairs at a time. In how many ways can you reach stair n?
By hand, think about your last move: you came from stair n − 1 (a 1-step) or from stair n − 2 (a 2-step). So ways(n) = ways(n − 1) + ways(n − 2).
| n | how you get there | ways(n) | Fibonacci |
|---|---|---|---|
| 0 | stand still, one way | 1 | F(1) = 1 |
| 1 | 1 | 1 | F(2) = 1 |
| 2 | 1+1, 2 | 2 | F(3) = 2 |
| 3 | from 2 (2 ways) or from 1 (1 way) | 3 | F(4) = 3 |
| 4 | 3 + 2 | 5 | F(5) = 5 |
| 5 | 5 + 3 | 8 | F(6) = 8 |
| 6 | 8 + 5 | 13 | F(7) = 13 |
The same rule as Fibonacci, but it starts one place later: ways(0) = 1 = F(1) and ways(1) = 1 = F(2). Each next term adds the same two neighbours, so the shift stays forever: ways(n) = F(n + 1). For 12 stairs the answer is F(13) = 233.
The brute force
Walk up the staircase, one stair at a time:
long long climbLoop(long long stairs) {
long long prev = 1, cur = 1; // ways(0), ways(1)
for (long long i = 2; i <= stairs; i++) {
long long next = (cur + prev) % MOD;
prev = cur;
cur = next;
}
return cur;
}It's correct and O(n). But what if there are 10¹⁸ stairs (answer mod 10⁹ + 7)? That's 10¹⁸ additions. At 10⁹ per second, about 30 years. Time limit exceeded.
The one thought that fixes it
Every stair applies the same step M. So 12 stairs means F(13), which sits in M¹³.
Stop at 13 and write it in binary: 1101 = 8 + 4 + 1. Powers add when you multiply: M^a · M^b = M^(a+b). So
M¹³ = M⁸ · M⁴ · M¹.
And M¹, M⁴, M⁸ are exactly what the squaring table produces. We skip M² because bit 1 of 13 is off. Three squarings plus three multiplications instead of 13 steps. For 10¹⁸, n has 60 bits, so it's about 120 multiplications of 2 × 2 matrices.
The code for the problem
long long climb(long long stairs) { // ways(n) = F(n + 1)
Mat M = {{1, 1}, {1, 0}};
return power(M, stairs + 1)[0][1];
}Dry run
Raise M to 13. Bits of 13 from the lowest: 1, 0, 1, 1.
| bit of 13 | base | what happens | result |
|---|---|---|---|
| 1 | M¹ | bit on: result = I · M¹ | M¹ = [[1, 1], [1, 0]] |
| 0 | M² | bit off: skip | M¹ |
| 1 | M⁴ | bit on: result = M¹ · M⁴ | M⁵ = [[8, 5], [5, 3]] |
| 1 | M⁸ | bit on: result = M⁵ · M⁸ | M¹³ = [[377, 233], [233, 144]] |
The answer is entry [0][1] = F(13) = 233, the same answer as the loop. For 10¹⁸ stairs the while runs 60 times and prints 680057396 (mod 10⁹ + 7).
Why it's O(k³ log n)
Count multiplications. The loop runs once per bit of n, about log₂ n times, and each round does at most two matrix products. A k × k product is k³ multiply-adds (here k = 2, so 8). Total O(k³ log n). Every entry stays below MOD ≈ 10⁹, so a product of two is below 10¹⁸ and fits in long long.
From 10¹⁸ steps down to 60 rounds, by squaring the step instead of repeating it.
A plain number to a power? A 1 × 1 matrix
power({{3}}, 13) gives 3¹³ = 1,594,323. That's fast power on numbers: the same loop, with k = 1.
A longer recurrence? A bigger matrix
Dice Combinations: in how many ways can dice throws add up to n? The last throw was 1…6, so dp[i] = dp[i − 1] + … + dp[i − 6]. The state is the last six values, so M is 6 × 6: row 0 adds all six, and the other rows shift each value down one slot.
Mat D(6, vector<long long>(6, 0));
for (int j = 0; j < 6; j++) D[0][j] = 1; // new dp = sum of the last six
for (int i = 1; i < 6; i++) D[i][i - 1] = 1; // every other term moves down one slotpower(D, n)[0][0] gives 4 ways for n = 3 and 32 for n = 6, the same as the DP.
Walks on a graph? The adjacency matrix
Put A[u][v] = 1 when there's an edge u → v. Then entry (u, v) of Aᵏ counts the walks of exactly k edges from u to v. Knight Dialer is this on the 10 phone keys: summing every entry of A² gives 46 numbers of length 3.
Remember this
- A recurrence with a fixed number of earlier terms, and n up to 10¹⁸: build M, raise it.
- The state must hold every term the next step needs; row i of M builds new term i.
- Start
resultat the identity, not at M, and reduce mod after every multiply-add. - Whenever a problem asks for "the n-th term" with a huge n, or "walks of exactly k steps", it's matrix power.
Practise it on Fibonacci Number, then Climbing Stairs (ways(n) = F(n + 1)), Fibonacci Numbers (n up to 10¹⁸), Throwing Dice (the 6 × 6 matrix), Knight Dialer (walks on a graph) and Graph Paths I.
Watch it work, line by line
Fibonacci at a huge index ↗, n = 13 → 233. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is n huge (up to 10¹⁸) while every step applies the same linear rule to a small state of a few numbers?
Reach for it when
- +n up to 1e18 with a small linear recurrence
- +number of walks of length exactly n
- +DP with constant-size state and same transition every step
- +state size k <= ~100
It fails when
- ×Transition changes with iuse Plain DP
- ×Transitions are non-linear (min-plus/max-plus semirings still work)use Plain DP or another method
- ×n is moderate (e.g. 5000)use Plain DP is enough
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What does Mⁿ look like for M = [[1, 1], [1, 0]]?Reveal
[[F(n+1), F(n)], [F(n), F(n−1)]].
2What does matrix fast power cost for a k × k state?Reveal
O(k³ log n): log₂ n squarings, each a k³ multiply.
3When is this the wrong tool?Reveal
When n is small enough for a loop (up to about 10⁷), or when the step rule changes with i or isn't linear.
Practice ladder
- 1Pow(x, n)fast power on a numberMedium
- 2Fibonacci Numberthe 2 × 2 matrixEasy
- 3Fibonacci Numbersthe hookMedium
- 4Throwing Dicea longer recurrenceMedium
- 5Knight Dialerwalks on a graphMedium
- 6Graph Paths Iadjacency matrix powerMedium
- 7Graph Paths IImin-plusMedium
- 8String Transformation by Rotations in Exactly k Stepscollapse statesHard
Finished Matrix Exponentiation? Mark it done and Lessgo moves you to the next step.