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 Theory

Linear 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

  1. Express the recurrence as a matrix equation: [F(n+1), F(n)] = M · [F(n), F(n−1)] with M = [[1,1],[1,0]].
  2. 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.
  3. Each 2×2 matrix product takes constant work, so the total cost is O(log n).
  4. 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.

Number Theory: Matrix ExponentiationO(log n)
F(n) from M^n by repeated squaring — recurrences in O(log n).
1
1
1
0
n6
Step 1 / 9
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Matrix exponentiation: F(6) = (M^6)[0][1] with M = [[1,1],[1,0]].
Python · Number Theory in Code
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

BestO(log n) multiplications
AverageO(log n)
WorstO(log n) — each O(1) for 2×2
SpaceO(1) beyond the matrices themselves

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.