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 for an matrix using binary exponentiation in .
How It Works
Same idea as scalar binary exponentiation but with matrix multiplication:
Recurrence to Matrix
For a linear recurrence , define:
Then where is the initial state vector.