Matrix Exponentiation
Matrix exponentiation turns one step of a linear recurrence into a matrix product, then raises that matrix to the nth power by repeated squaring. Fibonacci, tiling counts and walk counts with huge n drop from O(n) steps to O(log n) products.
What Matrix Exponentiation Does
Matrix exponentiation finds the nth term of a recurrence with fixed coefficients without stepping through all n terms. One step of the recurrence becomes multiplication by a fixed matrix M, so n steps are Mⁿ, and Mⁿ can be computed with about log₂ n squarings. That is how competitive programmers get Fibonacci in log n time for n as large as 10¹⁸.
It works for any recurrence where the next value is a fixed linear combination of the last k values, and for any process with a fixed set of states and fixed transitions: counting tilings, walks of length n in a graph, or strings accepted by a small automaton.
- Linear recurrence → state vector × matrix
- Huge n → O(log n) products
From Recurrence to Matrix
For Fibonacci, keep the state [F(n), F(n−1)]. The next state is [F(n) + F(n−1), F(n)], which is M × state with M = [[1, 1], [1, 0]]: the top row adds, the bottom row copies. Applying it n times gives Mⁿ = [[F(n+1), F(n)], [F(n), F(n−1)]].
For a general order-k recurrence a(n) = c₁·a(n−1) + … + cₖ·a(n−k), build the companion matrix: the first row is c₁ … cₖ, and the rows below are a shifted identity that moves each older value down one slot. For a(n) = a(n−1) + 2·a(n−2) that is [[1, 2], [1, 0]]. Always multiply once by hand and check that it turns [a(1), a(0)] into [a(2), a(1)].
- Top row: the coefficients
- Below: shift the older values down
Raising the Matrix to a Power
- Set result = I (the identity matrix) and base = M
- While n > 0: if the lowest bit of n is 1, set result = result × base
- Square the base: base = base × base
- Shift n right by one bit (n = n / 2)
- Read the answer from the right cell of result
This is the squaring trick from number theory basics applied to matrices. It works because matrix multiplication is associative, so M¹⁰ = M⁸ · M² no matter how the products are grouped. Throughout the loop, result × baseⁿ equals the target power, and when n reaches 0 result holds the answer.
In the tracer, 10 = 1010 in binary: the base runs M, M², M⁴, M⁸, and only M² and M⁸ are multiplied in, giving M¹⁰ = [[89, 55], [55, 34]] and F(10) = 55. Matrix products are not commutative in general, but all powers of one matrix commute with each other, so result × base and base × result give the same answer here.
- Identity plays the role of 1
- One squaring per bit, one multiply per 1 bit
Terms, operations, and practical uses
Modelling
- State vectorThe last k values of the recurrence, newest first, e.g. [F(n), F(n−1)].
- Transition matrixThe fixed matrix that turns one state into the next with a single product.
- Companion matrixCoefficients in the first row, a shifted identity below. Encodes any order-k linear recurrence.
Powering
- Identity matrix1s on the diagonal, 0s elsewhere. M⁰ = I, and multiplying by I changes nothing.
- Repeated squaringM, M², M⁴, M⁸, …: one squaring per bit of n; multiply the ones whose bit is 1.
- Associativity(AB)C = A(BC). It is why splitting n into powers of two gives the same matrix.
Limits
- O(d³ log n)log n rounds, each with up to two d×d products of d³ multiplications.
- ModulusReduce every cell so values stay below the integer limit; 10⁹ + 7 is the usual choice.
- Walk count(Aᵏ)[i][j] is the number of k-edge walks from i to j in a graph with adjacency matrix A.
Code in Python, C++ and Java
MOD = 1_000_000_007
def mat_mul(a, b, mod):
n = len(a)
c = [[0] * n for _ in range(n)]
for i in range(n):
for k in range(n):
for j in range(n):
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % mod
return c
def mat_pow(m, n, mod):
result = [[int(i == j) for j in range(len(m))] for i in range(len(m))]
while n > 0:
if n & 1:
result = mat_mul(result, m, mod)
m = mat_mul(m, m, mod)
n >>= 1
return result
def fib(n, mod):
return mat_pow([[1, 1], [1, 0]], n, mod)[0][1]
print("F(10) =", fib(10, MOD))
print("F(100) mod 1000000007 =", fib(100, MOD))#include <iostream>
#include <vector>
using namespace std;
using Matrix = vector<vector<long long>>;
const long long MOD = 1000000007;
Matrix matMul(const Matrix& a, const Matrix& b) {
int n = a.size();
Matrix c(n, vector<long long>(n, 0));
for (int i = 0; i < n; i++)
for (int k = 0; k < n; k++)
for (int j = 0; j < n; j++)
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
return c;
}
Matrix matPow(Matrix m, long long n) {
int d = m.size();
Matrix result(d, vector<long long>(d, 0));
for (int i = 0; i < d; i++) result[i][i] = 1;
while (n > 0) {
if (n & 1) result = matMul(result, m);
m = matMul(m, m);
n >>= 1;
}
return result;
}
long long fib(long long n) {
return matPow({{1, 1}, {1, 0}}, n)[0][1];
}
int main() {
cout << "F(10) = " << fib(10) << "\n";
cout << "F(100) mod 1000000007 = " << fib(100) << "\n";
}public class Main {
static final long MOD = 1_000_000_007L;
static long[][] matMul(long[][] a, long[][] b) {
int n = a.length;
long[][] c = new long[n][n];
for (int i = 0; i < n; i++)
for (int k = 0; k < n; k++)
for (int j = 0; j < n; j++)
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
return c;
}
static long[][] matPow(long[][] m, long n) {
int d = m.length;
long[][] result = new long[d][d];
for (int i = 0; i < d; i++) result[i][i] = 1;
while (n > 0) {
if ((n & 1) == 1) result = matMul(result, m);
m = matMul(m, m);
n >>= 1;
}
return result;
}
static long fib(long n) {
return matPow(new long[][] {{1, 1}, {1, 0}}, n)[0][1];
}
public static void main(String[] args) {
System.out.println("F(10) = " + fib(10));
System.out.println("F(100) mod 1000000007 = " + fib(100));
}
}Step through it
Running on M = [[1, 1], [1, 0]], n = 10
Time Complexity
The loop runs ⌊log₂ n⌋ + 1 rounds with at most two matrix products each. A d×d product with the usual triple loop costs d³ multiplications, so the total is O(d³ log n) time and O(d²) memory. For Fibonacci, d = 2 and n = 10¹⁸ needs about 120 small products instead of 10¹⁸ additions.
The d³ factor matters: a 100×100 matrix costs 10⁶ per product, about 10⁸ for n = 10¹⁸, which is fine, but a 1,000-state system is not. If only one starting vector is needed and n is moderate, plain stepping (O(d² n), or O(k·n) for a recurrence) may simply be cheaper.
- O(d³ log n) time, O(d²) space
- Worth it when n is large and d is small
Working Modulo m
Fibonacci numbers grow fast: F(93) already overflows a signed 64-bit integer. Problems with huge n therefore ask for the answer modulo a prime, usually 10⁹ + 7. Reduce every cell after each product. With m = 10⁹ + 7, each term a·b is below about 10¹⁸ and a 2×2 cell adds two of them, still under 2⁶³ ≈ 9.2 × 10¹⁸; for larger d, reduce after every term. Modular arithmetic covers the rules, including keeping negative coefficients in the range 0 … m − 1.
- Reduce each cell, every product
- Normalise negative coefficients
Where It Is Used
Walk counting: entry (i, j) of Aᵏ, for an adjacency matrix A, is the number of walks of exactly k edges from i to j. Tiling and DP with fixed transitions: if a DP moves between a small, fixed set of states the same way at every step, its transition table is a matrix, as in domino tilings of a 3×n board or Climbing Stairs with huge n. Affine recurrences like a(n) = a(n−1) + 5 need one extra state that always stays 1, so the constant can be added by the matrix.
It does not apply when the coefficients change with n, unless the changes repeat in a fixed cycle (then power the product of one cycle). Rectangular matrices cannot be powered at all. See also recurrence relations and the Fibonacci Number problem.
- Aᵏ counts length-k walks
- Fixed transitions only
Edge Cases and Bugs
Wrong cell: the top-left of Mⁿ is F(n+1), not F(n); check the mapping with n = 1. Wrong exponent: if the state starts at index b, you need Mⁿ⁻ᵇ, not Mⁿ. State order: the companion matrix expects newest value first; feeding [a(0), a(1)] gives a(2) = 2 instead of 1. n = 0 must return I, so the answer is the starting state itself.
Test n = 0, 1 and 2, a 1×1 matrix (it reduces to ordinary powering), and compare the first 20 terms against a plain loop. Floating-point matrices drift under repeated squaring; integer recurrences should stay in exact or modular arithmetic.
- Check n = 0, 1, 2 against a loop
- Newest value first in the state