Algorithms · Visualized
Number Theory: Matrix Exponentiation
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Linear recurrences like Fibonacci can be expressed as repeated multiplication by a fixed transformation matrix. Time: O(log n) average, O(log n) — each O(1) for 2×2 worst; space: O(1) beyond the matrices themselves.
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Matrix Exponentiation (Fast Fibonacci)
Number TheoryLinear recurrences like Fibonacci can be expressed as repeated multiplication by a fixed transformation matrix. Fast exponentiation (repeated squaring) on that matrix computes the n-th term in O(log n) multiplications instead of O(n) additions.
How Matrix Exponentiation Works
- Express the recurrence as a matrix equation: [F(n+1), F(n)] = M · [F(n), F(n−1)] with M = [[1,1],[1,0]].
- To find F(n), compute M^n by repeated squaring, multiplying the base into the result whenever the current bit of the exponent is set.
- Each 2×2 matrix product takes constant work, so the total cost is O(log n).
- Read F(n) off the resulting matrix — the top-right (or bottom-left) entry.
Matrix Exponentiation Worked Example
Input: {n: 6}
n = 6 = 110₂. Square the base: M² = [[2,1],[1,1]], M⁴ = [[5,3],[3,2]]. Bit 1 set → result = M²; bit 2 set → result = M² × M⁴ = M⁶ = [[13,8],[8,5]]. The top-right entry gives F(6) = 8 — matching the Fibonacci sequence.
def mat_mul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
def mat_pow(mat, n):
res = [[1, 0], [0, 1]]
while n:
if n & 1:
res = mat_mul(res, mat)
mat = mat_mul(mat, mat)
n >>= 1
return res
def fib(n):
return mat_pow([[1, 1], [1, 0]], n)[0][1]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Matrix Exponentiation Time & Space Complexity
When to Use Matrix Exponentiation
- Computing huge Fibonacci-like terms modulo a prime (competitive programming).
- Solving linear recurrence relations efficiently.
- Modeling linear dynamical systems.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.