guest@itl:~/home/number-theory$
templates/matrix-exponentiation.cpp
compilable
$cat templates/matrix-exponentiation

Matrix Exponentiation

Binary exponentiation on square matrices for solving linear recurrences in O(n^3 log k).

#matrix#exponentiation#linear-recurrence#fibonacci
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

const ll MOD = 1e9 + 7;

struct Matrix {
    int n;
    vector<vector<ll>> mat;

    Matrix(int _n, bool identity = false) : n(_n), mat(_n, vector<ll>(_n, 0)) {
        if (identity)
            for (int i = 0; i < n; i++) mat[i][i] = 1;
    }

    Matrix operator*(const Matrix &o) const {
        Matrix res(n);
        for (int i = 0; i < n; i++)
            for (int k = 0; k < n; k++) {
                if (!mat[i][k]) continue;
                for (int j = 0; j < n; j++)
                    res.mat[i][j] = (res.mat[i][j] + mat[i][k] * o.mat[k][j]) % MOD;
            }
        return res;
    }

    Matrix pow(ll e) const {
        Matrix res(n, true), base = *this;
        while (e > 0) {
            if (e & 1) res = res * base;
            base = base * base;
            e >>= 1;
        }
        return res;
    }
};
36 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Matrix Exponentiation

Compute MkM^k for an n×nn \times n matrix using binary exponentiation in O(n3logk)O(n^3 \log k).

How It Works

Same idea as scalar binary exponentiation but with matrix multiplication:

  • Start with identity matrix II

  • Decompose kk in binary, square MM repeatedly, multiply into result when bit is 1
  • Recurrence to Matrix

    For a linear recurrence an=c1an1+c2an2++ckanka_n = c_1 a_{n-1} + c_2 a_{n-2} + \dots + c_k a_{n-k}, define:

    A=(c1c2ck1000100)A = \begin{pmatrix} c_1 & c_2 & \cdots & c_k \\ 1 & 0 & \cdots & 0 \\ 0 & 1 & \cdots & 0 \\ \vdots & & \ddots & 0 \end{pmatrix}

    Then vn=Anv0v_n = A^n \cdot v_0 where v0v_0 is the initial state vector.

    When to Use

  • Fibonacci / Lucas numbers for nn up to 101810^{18}

  • Any fixed-order linear recurrence where nn is too large for DP

  • Counting paths of length kk in a graph via adjacency matrix powers

  • State machine transitions raised to a large power
  • Complexity

  • Time — O(n3logk)O(n^3 \log k) where nn is matrix size and kk is exponent

  • Space — O(n2)O(n^2)