Skip to lesson

Matrix exponentiation: linear recurrences in logarithmic time

When a dynamic programming recurrence is linear and N is as large as 10^18, iterating sequentially takes decades. We start with plain loops to see why linear scans fail, and then formulate matrix multiplication to compute answers in logarithmic time.

Brute Force Iteration and Why It Fails for Huge N

Plain iteration finds the N-th Fibonacci number by storing the last two values and running a loop from 2 to N: next = (prev1 + prev2) % MOD.

Java
static final int MOD = 1_000_000_007;
long fib(long n) {    if (n < 2) return n;    long prev2 = 0, prev1 = 1;    for (long i = 2; i <= n; i++) {   // N steps: hopeless for N = 10^18        long next = (prev1 + prev2) % MOD;        prev2 = prev1;        prev1 = next;    }    return prev1;}

Why does this fail when N is 10^18? Modern CPUs execute roughly 10^9 operations per second. A loop running 10^18 iterations would require 1 billion seconds—over 31 years of continuous computation!

Whenever constraints state N <= 10^18, an algorithm with O(N) time complexity is unusable. We need a technique whose runtime scales with the number of bits in N rather than N itself.

Constructing the Transition Matrix

Any linear recurrence F(n) = c1F(n-1) + c2F(n-2) + ... + ck*F(n-k) can be written as a matrix-vector product. We define a state column vector holding the k most recent terms: V(n) = [F(n), F(n-1), ..., F(n-k+1)]^T.

FibStep.javaJava
public class FibStep {    public static void main(String[] args) {        long[][] m = {{1, 1}, {1, 0}}; // top row: coefficients of F(n-1), F(n-2)        long[] v = {1, 0};              // V(1) = [F(1), F(0)]        for (int step = 2; step <= 6; step++) {            long[] next = {m[0][0] * v[0] + m[0][1] * v[1],                           m[1][0] * v[0] + m[1][1] * v[1]};            v = next;                   // V(step) = M * V(step - 1)        }        System.out.println("V(6) = [" + v[0] + ", " + v[1] + "]");    }}
Output
V(6) = [8, 5]

To advance from V(n-1) to V(n), we multiply by a k x k transition matrix M. The top row of M contains the recurrence coefficients [c1, c2, ..., ck], while each subsequent row shifts previous terms down using identity sub-diagonals.

For Fibonacci where F(n) = F(n-1) + F(n-2), the transition matrix is M = [[1, 1], [1, 0]]. Applying this relation repeatedly gives V(n) = M^(n-1) * V(1).

Binary Matrix Exponentiation

Instead of multiplying matrix M by itself n - 1 times sequentially, we use binary exponentiation (repeated squaring). To compute M^13, we express 13 in binary as 8 + 4 + 1 and multiply the corresponding powers.

Example 1 · Fibonacci with matrix power, optimal: O(log N) time, O(1) space

FibonacciMatrixDemo.javaJava
public class FibonacciMatrixDemo {    private static final int MOD = 1_000_000_007;
    public static int fib(long n) {        if (n == 0) return 0;        if (n == 1) return 1;
        long[][] m = {{1, 1}, {1, 0}};        long[][] result = power(m, n - 1);        return (int) result[0][0];    }
    private static long[][] multiply(long[][] a, long[][] b) {        long[][] c = new long[2][2];        for (int i = 0; i < 2; i++) {            for (int k = 0; k < 2; k++) {                for (int j = 0; j < 2; j++) {                    c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;                }            }        }        return c;    }
    private static long[][] power(long[][] m, long exp) {        long[][] res = {{1, 0}, {0, 1}}; // Identity        long[][] base = m;        while (exp > 0) {            if ((exp & 1) == 1) res = multiply(res, base);            base = multiply(base, base);            exp >>= 1;        }        return res;    }
    public static void main(String[] args) {        System.out.println("Fib(10): " + fib(10));        System.out.println("Fib(50): " + fib(50));    }}
Output
Fib(10): 55
Fib(50): 586268941

What this code does

  • Uses 2x2 transition matrix [[1, 1], [1, 0]] corresponding to F(n) = F(n-1) + F(n-2).
  • Computes matrix power via binary exponentiation in O(2^3 * log n) = O(log n) operations.
  • Handles n up to 10^18 with modular arithmetic without intermediate overflow.
  • Why faster: squaring the matrix doubles the power each time, so about log2(N) multiplications of a 2 × 2 matrix replace N additions.

Example 2 · Fibonacci with plain recursion, brute force: O(2^N) time, O(N) space

FibRecursionDemo.javaJava
public class FibRecursionDemo {    static long fib(int n) {        if (n < 2) return n;        return fib(n - 1) + fib(n - 2);                  // the same values are rebuilt again and again    }
    public static void main(String[] args) {        System.out.println("Fib(10): " + fib(10));        System.out.println("Fib(30): " + fib(30));    }}
Output
Fib(10): 55
Fib(30): 832040

What this code does

  • fib(n) calls fib(n - 1) and fib(n - 2), so the same values are rebuilt many times.
  • fib(30) already needs over a million calls; fib(50) would take hours.

Example 3 · Fibonacci with a loop, better: O(N) time, O(1) space

FibLoopDemo.javaJava
public class FibLoopDemo {    static final long MOD = 1_000_000_007L;
    static long fib(long n) {        long prev = 0, curr = 1;        for (long i = 0; i < n; i++) {                   // one step per index: N steps            long next = (prev + curr) % MOD;            prev = curr;            curr = next;        }        return prev;    }
    public static void main(String[] args) {        System.out.println("Fib(10): " + fib(10));        System.out.println("Fib(50): " + fib(50));    }}
Output
Fib(10): 55
Fib(50): 586268941

What this code does

  • prev and curr hold two neighbouring Fibonacci numbers; each step moves both one place along.
  • The modulus keeps every value inside a long.
  • It is fast for N = 50 but needs 10^18 steps for N = 10^18. Matrix power needs about 60 multiplications.

Example 4 · Tribonacci with matrix power: O(log N) time, O(1) space

TribonacciMatrixDemo.javaJava
public class TribonacciMatrixDemo {    private static final int MOD = 1_000_000_007;
    public static int tribonacci(long n) {        if (n == 0) return 0;        if (n == 1 || n == 2) return 1;
        long[][] m = {            {1, 1, 1},            {1, 0, 0},            {0, 1, 0}        };        long[][] res = power(m, n - 2, 3);        // Vector V(2) = [T(2)=1, T(1)=1, T(0)=0]^T        long ans = (res[0][0] * 1 + res[0][1] * 1 + res[0][2] * 0) % MOD;        return (int) ans;    }
    private static long[][] multiply(long[][] a, long[][] b, int k) {        long[][] c = new long[k][k];        for (int i = 0; i < k; i++) {            for (int p = 0; p < k; p++) {                for (int j = 0; j < k; j++) {                    c[i][j] = (c[i][j] + a[i][p] * b[p][j]) % MOD;                }            }        }        return c;    }
    private static long[][] power(long[][] m, long exp, int k) {        long[][] res = new long[k][k];        for (int i = 0; i < k; i++) res[i][i] = 1; // Identity        long[][] base = m;        while (exp > 0) {            if ((exp & 1) == 1) res = multiply(res, base, k);            base = multiply(base, base, k);            exp >>= 1;        }        return res;    }
    public static void main(String[] args) {        System.out.println("Tribonacci(4): " + tribonacci(4));        System.out.println("Tribonacci(7): " + tribonacci(7));    }}
Output
Tribonacci(4): 4
Tribonacci(7): 24

What this code does

  • State vector has size 3: [T(n), T(n-1), T(n-2)]^T.
  • Transition matrix has dimension 3x3 with top row coefficients [1, 1, 1].
  • Executes in O(3^3 * log n) time.

Squaring the matrix at each step computes powers M^1, M^2, M^4, M^8 in just log2(N) matrix multiplications. For N = 10^18, log2(N) is approximately 60 operations. Multiplying two k x k matrices takes O(k^3) arithmetic operations. The overall time complexity becomes O(k^3 * log N), running in less than a single millisecond.

Fix the error

Fix the compile error

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

This copies one cell of a 2 x 2 transition matrix.

public class PowerFix {
public static void main(String[] args) {
long[][] base = {{1, 1}, {1, 0}};
long[][] copy = new long[2][2];
copy[0][0] = base[0][0]
System.out.println(copy[0][0]);
}
}

Error

PowerFix.java:5: error: ';' expected
        copy[0][0] = base[0][0]
                               ^

Counting Graph Walks of Length K

Matrix exponentiation extends naturally to graph theory. If A is the adjacency matrix of a graph where A[i][j] is the number of directed edges from i to j, then (A^k)[i][j] gives the exact number of walks of length k from i to j.

Example 5 · Graph walks by following every edge, brute force: O(V^K) time, O(K) space

WalksBruteDemo.javaJava
public class WalksBruteDemo {    static long walks(long[][] adj, int from, int to, int steps) {        if (steps == 0) return from == to ? 1 : 0;        long total = 0;        for (int next = 0; next < adj.length; next++) {            if (adj[from][next] == 1) {                total += walks(adj, next, to, steps - 1);  // follow every edge, one step at a time            }        }        return total;    }
    public static void main(String[] args) {        long[][] adj = {            {0, 1, 1},            {0, 0, 1},            {1, 0, 0}        };        System.out.println("Walks of length 3 from 0 to 2: " + walks(adj, 0, 2, 3));    }}
Output
Walks of length 3 from 0 to 2: 1

What this code does

  • walks(from, to, steps) follows each edge out of from and counts the walks from the next vertex.
  • With steps = 0 it returns 1 only when we stand on the target vertex.
  • The answer 1 matches the matrix power, but the number of paths explodes with K.

Example 6 · Graph walks with matrix power, optimal: O(V³ · log K) time, O(V²) space

GraphPathCountMatrixDemo.javaJava
public class GraphPathCountMatrixDemo {    public static long countWalks(long[][] adj, int k, int u, int v) {        int n = adj.length;        long[][] res = new long[n][n];        for (int i = 0; i < n; i++) res[i][i] = 1;        long[][] base = adj;        long exp = k;
        while (exp > 0) {            if ((exp & 1) == 1) res = multiply(res, base, n);            base = multiply(base, base, n);            exp >>= 1;        }        return res[u][v];    }
    private static long[][] multiply(long[][] a, long[][] b, int n) {        long[][] c = new long[n][n];        for (int i = 0; i < n; i++) {            for (int p = 0; p < n; p++) {                for (int j = 0; j < n; j++) {                    c[i][j] += a[i][p] * b[p][j];                }            }        }        return c;    }
    public static void main(String[] args) {        long[][] adj = {            {0, 1, 1},            {0, 0, 1},            {1, 0, 0}        };        System.out.println("Walks of length 3 from 0 to 2: " + countWalks(adj, 3, 0, 2));    }}
Output
Walks of length 3 from 0 to 2: 1

What this code does

  • The k-th power of adjacency matrix A gives exact path counts of length k.
  • Walk 1: 0 -> 1 -> 2 -> 0 -> 2 (wait: length 3 is 0->1->2->...: 0->2->0->2 and 0->1->2->...)
  • Evaluates in O(V^3 * log k) time.
  • Why faster: the matrix power counts walks through every middle vertex at once, and log K squarings replace V^K recursive paths.

Why does this hold? Multiplying A by itself sums over all intermediate vertices v: sum(A[i][v] * A[v][j]), which matches the definition of extending a path by one edge. Problems asking for paths of length 10^9 in small graphs with up to 100 vertices are solved directly by raising the adjacency matrix to power 10^9 modulo 1,000,000,007.

Next step

Check your understanding

10 quick questions