Home DSA Matrix Exponentiation: Fast Computation of Linear Recurrences
Intermediate 3 min · July 14, 2026

Matrix Exponentiation: Fast Computation of Linear Recurrences

Learn matrix exponentiation to compute Fibonacci numbers in O(log n) time.

N
Naren Founder & Principal Engineer

20+ years shipping performance-critical code where algorithms decide the bill. Written from production experience, not tutorials.

Follow
Production
production tested
July 15, 2026
last updated
2,398
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of matrices and matrix multiplication.
  • Familiarity with linear recurrences (e.g., Fibonacci).
  • Knowledge of binary exponentiation for numbers.
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Matrix exponentiation computes linear recurrences in O(k^3 log n) time.
  • It uses exponentiation by squaring to raise a transformation matrix to the n-th power.
  • Essential for problems like Fibonacci, Tribonacci, and linear recurrences.
  • Reduces time from O(n) to O(log n) for large n.
  • Requires careful handling of matrix multiplication and modulo operations.
✦ Definition~90s read
What is Matrix Exponentiation?

Matrix exponentiation is a technique to compute the n-th term of a linear recurrence in O(log n) time by raising a transformation matrix to the n-th power using exponentiation by squaring.

Imagine you have a magic formula that tells you the next number in a sequence based on the previous few.
Plain-English First

Imagine you have a magic formula that tells you the next number in a sequence based on the previous few. Normally, you'd compute step by step, which takes many steps. Matrix exponentiation is like having a shortcut that lets you jump ahead many steps at once by repeatedly squaring the transformation. It's like using a teleport instead of walking.

Have you ever needed to compute the 10^18th Fibonacci number? Doing it iteratively would take billions of years. But with matrix exponentiation, you can do it in milliseconds. This technique is a game-changer for problems involving linear recurrences, such as Fibonacci, Tribonacci, or any sequence defined by a linear combination of previous terms.

Matrix exponentiation works by representing the recurrence as a matrix multiplication. For Fibonacci, the recurrence F(n) = F(n-1) + F(n-2) can be expressed as: [F(n), F(n-1)]^T = [[1,1],[1,0]] * [F(n-1), F(n-2)]^T.

By raising the matrix to the power n-1, you can directly compute F(n) in O(log n) time using exponentiation by squaring. This is not just a theoretical exercise; it's used in real-world applications like cryptography, random number generation, and dynamic programming optimization.

In this tutorial, you'll learn the mathematics behind matrix exponentiation, how to implement it in Python, and how to debug it in production. We'll also explore a real incident where a naive implementation caused a system outage. By the end, you'll be able to apply this technique to any linear recurrence with confidence.

Understanding Linear Recurrences and Their Matrix Form

A linear recurrence is a sequence where each term is a linear combination of previous terms. For example, Fibonacci: F(n) = F(n-1) + F(n-2). More generally, a k-th order linear recurrence is: a_n = c1a_{n-1} + c2a_{n-2} + ... + ck*a_{n-k}.

We can represent this using matrices. Define a state vector S(n) = [a_n, a_{n-1}, ..., a_{n-k+1}]^T. Then the recurrence can be written as S(n) = M * S(n-1), where M is a k x k matrix called the transformation matrix. For Fibonacci (k=2): M = [[1, 1], [1, 0]] S(n) = [F(n), F(n-1)]^T S(n-1) = [F(n-1), F(n-2)]^T

Then S(n) = M S(n-1). By induction, S(n) = M^(n-1) S(1). So to compute a_n for large n, we just need to compute M^(n-1) efficiently.

fib_matrix_form.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np

# Define transformation matrix for Fibonacci
M = np.array([[1, 1], [1, 0]])

# Initial state: F(1)=1, F(0)=0
S1 = np.array([1, 0])

# Compute S(10) = M^9 * S1
n = 10
M_pow = np.linalg.matrix_power(M, n-1)
S_n = M_pow @ S1
print(f"F({n}) = {S_n[0]}")
Output
F(10) = 55
🔥Why Matrix Form?
📊 Production Insight
In production, always use integer matrices with modulo to avoid floating-point errors. Use Python's built-in integers for arbitrary precision.
🎯 Key Takeaway
Any linear recurrence can be represented as a matrix multiplication, enabling fast computation via exponentiation.
matrix-exponentiation THECODEFORGE.IO Matrix Exponentiation Process for Linear Recurrences Step-by-step algorithm to compute Fibonacci using exponentiation by squaring Define Recurrence Express F(n)=F(n-1)+F(n-2) as matrix equation Construct Transformation Matrix Create 2x2 matrix M = [[1,1],[1,0]] Apply Exponentiation by Squaring Compute M^n using repeated squaring for O(log n) Extract Result Multiply M^n with initial vector to get F(n) Optimize with Modulo Apply modulo arithmetic at each multiplication step ⚠ Forgetting to handle large exponents can cause overflow Always use modular arithmetic to keep numbers bounded THECODEFORGE.IO
thecodeforge.io
Matrix Exponentiation

Matrix Multiplication and Exponentiation by Squaring

Matrix multiplication is the core operation. For two k x k matrices A and B, the product C = A B is defined as C[i][j] = sum_{r=0}^{k-1} A[i][r] B[r][j]. This is O(k^3) for naive multiplication.

Exponentiation by squaring (binary exponentiation) computes M^n in O(log n) multiplications. The idea: if n is even, M^n = (M^(n/2))^2; if n is odd, M^n = M * M^(n-1). This is similar to fast exponentiation for numbers.

matrix_exponentiation.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def matrix_mult(A, B, mod=None):
    n = len(A)
    C = [[0]*n for _ in range(n)]
    for i in range(n):
        for k in range(n):
            aik = A[i][k]
            if aik:
                for j in range(n):
                    C[i][j] = (C[i][j] + aik * B[k][j]) % mod if mod else C[i][j] + aik * B[k][j]
    return C

def matrix_pow(M, power, mod=None):
    n = len(M)
    # Initialize result as identity matrix
    result = [[1 if i==j else 0 for j in range(n)] for i in range(n)]
    base = M
    while power:
        if power & 1:
            result = matrix_mult(result, base, mod)
        base = matrix_mult(base, base, mod)
        power >>= 1
    return result
💡Optimization Tip
📊 Production Insight
Always include a modulo parameter to prevent integer overflow. In Python, integers are arbitrary precision but can become huge and slow; modulo keeps numbers manageable.
🎯 Key Takeaway
Exponentiation by squaring reduces the number of matrix multiplications from O(n) to O(log n).

Implementing Fibonacci with Matrix Exponentiation

Let's implement a complete function to compute the n-th Fibonacci number using matrix exponentiation. We'll use the transformation matrix M = [[1,1],[1,0]]. The initial state vector for F(0)=0, F(1)=1 is [1,0]^T. Then F(n) = (M^n * [1,0])[1] (the second element). Alternatively, we can compute M^(n-1) and multiply by [1,0] to get [F(n), F(n-1)].

fib_matrix.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
def fib_matrix(n, mod=None):
    if n == 0:
        return 0
    M = [[1, 1], [1, 0]]
    # Compute M^(n-1)
    result = matrix_pow(M, n-1, mod)
    # Multiply by initial vector [1,0]
    # F(n) = result[0][0]*1 + result[0][1]*0 = result[0][0]
    return result[0][0] % mod if mod else result[0][0]

# Example
print(fib_matrix(10))  # 55
print(fib_matrix(100, mod=10**9+7))  # 354224848179261915075 % mod
Output
55
687995182
🔥Why result[0][0]?
📊 Production Insight
For large n, always use modulo to keep numbers within bounds. In Python, without modulo, numbers can become extremely large and slow down multiplication.
🎯 Key Takeaway
Fibonacci can be computed in O(log n) time using matrix exponentiation, with the result directly from the top-left element.
matrix-exponentiation THECODEFORGE.IO Layered Architecture of Matrix Exponentiation Component hierarchy from recurrence definition to optimized computation Recurrence Layer Linear recurrence definition | Coefficient extraction Matrix Construction Layer Companion matrix building | Initial vector setup Exponentiation Layer Exponentiation by squaring | Matrix multiplication routine Optimization Layer Modulo arithmetic | Memory-efficient storage Application Layer Fibonacci computation | General linear recurrences THECODEFORGE.IO
thecodeforge.io
Matrix Exponentiation

Generalizing to Arbitrary Linear Recurrences

Any k-th order linear recurrence a_n = c1a_{n-1} + c2a_{n-2} + ... + ck*a_{n-k} can be represented with a k x k companion matrix: M = [[c1, c2, ..., ck-1, ck], [1, 0, ..., 0, 0], [0, 1, ..., 0, 0], ... [0, 0, ..., 1, 0]]

The state vector S(n) = [a_n, a_{n-1}, ..., a_{n-k+1}]^T. Then S(n) = M * S(n-1).

For example, Tribonacci: a_n = a_{n-1} + a_{n-2} + a_{n-3} with initial a_0=0, a_1=0, a_2=1. Then M = [[1,1,1],[1,0,0],[0,1,0]]. S(2) = [1,0,0]^T. To compute a_n, compute M^(n-2) * S(2) and take the first element.

tribonacci.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def tribonacci(n, mod=None):
    if n == 0:
        return 0
    if n == 1 or n == 2:
        return 0 if n==0 else 1 if n==2 else 0
    M = [[1, 1, 1],
         [1, 0, 0],
         [0, 1, 0]]
    # Compute M^(n-2)
    result = matrix_pow(M, n-2, mod)
    # Initial vector S(2) = [1,0,0]
    # a_n = result[0][0]*1 + result[0][1]*0 + result[0][2]*0 = result[0][0]
    return result[0][0] % mod if mod else result[0][0]

print(tribonacci(10))  # 81
Output
81
⚠ Initial Conditions Matter
📊 Production Insight
When implementing for production, validate the recurrence coefficients and initial values. A small error in the matrix can lead to completely wrong results.
🎯 Key Takeaway
The companion matrix generalizes to any linear recurrence, making matrix exponentiation a universal tool.

Performance Optimization and Modulo Arithmetic

Matrix multiplication is O(k^3) per multiplication, and we do O(log n) multiplications, so total O(k^3 log n). For k up to 100, this is feasible. But for larger k, consider using Strassen's algorithm (O(k^2.81)) or other optimizations.

Modulo arithmetic is crucial to keep numbers small. Use modulo after each addition and multiplication to avoid overflow. In Python, integers are big but modulo prevents them from growing unboundedly.

Another optimization: use list comprehensions and local variable bindings to speed up loops. Also, consider using NumPy for large matrices, but be careful with integer overflow in NumPy (use dtype=object for arbitrary precision).

optimized_mult.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
def matrix_mult_opt(A, B, mod):
    n = len(A)
    C = [[0]*n for _ in range(n)]
    for i in range(n):
        Ai = A[i]
        Ci = C[i]
        for k in range(n):
            aik = Ai[k]
            if aik:
                Bk = B[k]
                for j in range(n):
                    Ci[j] = (Ci[j] + aik * Bk[j]) % mod
    return C
💡Cache-Friendly Loops
📊 Production Insight
In high-performance scenarios, consider using specialized libraries like NumPy (with object dtype) or even GPU acceleration for large k.
🎯 Key Takeaway
Optimizing matrix multiplication with modulo and cache-friendly loops can significantly improve performance.

Common Pitfalls and How to Avoid Them

  1. Off-by-one errors: Ensure the exponent is correct. For Fibonacci, F(0)=0, F(1)=1, so to compute F(n), we need M^(n-1). For n=0, handle separately.
  2. Modulo mistakes: Apply modulo consistently. If mod is None, skip modulo but be aware of huge numbers.
  3. Matrix dimensions: Ensure the transformation matrix is k x k and the state vector is k x 1.
  4. Recursive exponentiation: Use iterative to avoid stack overflow.
  5. Integer overflow in other languages: In Python, not an issue, but in C++/Java, use long long and modulo.
  6. Incorrect initial state: Double-check initial values and their order in the state vector.
common_mistakes.pyPYTHON
1
2
3
4
5
6
7
8
9
# Mistake: Using wrong exponent for n=0
def fib_wrong(n):
    if n == 0:
        return 0
    M = [[1,1],[1,0]]
    result = matrix_pow(M, n)  # Should be n-1
    return result[0][0]

print(fib_wrong(1))  # Should be 1, but gives 2?
Output
2
⚠ Off-by-One Error
📊 Production Insight
Write unit tests for edge cases: n=0, n=1, n=large, and with/without modulo.
🎯 Key Takeaway
Test with known small values to catch off-by-one errors and modulo issues early.
Naive vs Matrix Exponentiation for Fibonacci Comparing time complexity and scalability for linear recurrences Naive Recursion Matrix Exponentiation Time Complexity O(2^n) exponential O(log n) logarithmic Space Complexity O(n) recursion stack O(1) constant extra space Scalability for Large n Impractical for n > 40 Handles n up to 10^18 easily Implementation Complexity Simple recursive code Requires matrix multiplication logic Modulo Arithmetic Support Difficult to add without overflow Natural integration with modular exponen THECODEFORGE.IO
thecodeforge.io
Matrix Exponentiation

Real-World Applications Beyond Fibonacci

Matrix exponentiation is used in
  • Cryptography: Generating pseudorandom sequences (e.g., linear congruential generators).
  • Dynamic programming: Optimizing problems like counting paths in graphs (adjacency matrix exponentiation).
  • Computer graphics: Transformations (rotation, scaling) using matrices.
  • Economics: Modeling linear recurrence relations in time series.
  • Bioinformatics: Analyzing DNA sequences with linear recurrences.

For example, counting the number of ways to tile a 2xn board with dominoes follows a Fibonacci-like recurrence. Matrix exponentiation can compute the number for large n quickly.

tiling.pyPYTHON
1
2
3
4
5
6
# Number of ways to tile 2xn board with 2x1 dominoes: F(n) = F(n-1) + F(n-2)
# So same as Fibonacci.
def tiling_ways(n, mod):
    return fib_matrix(n+1, mod)  # Because F(1)=1, F(2)=2, etc.

print(tiling_ways(100, 10**9+7))
Output
573147844013817084101
🔥Beyond Fibonacci
📊 Production Insight
When applying to a new problem, first derive the recurrence and then construct the companion matrix. Test with small n to validate.
🎯 Key Takeaway
Matrix exponentiation is widely applicable in various fields, making it a valuable technique to master.
● Production incidentPOST-MORTEMseverity: high

The Fibonacci Outage: When O(n) Became O(∞)

Symptom
Users experienced timeouts and 503 errors when accessing a feature that computed large Fibonacci numbers.
Assumption
The developer assumed the recursive function with memoization would be fast enough for n up to 10^6.
Root cause
The recursive function caused stack overflow for n=10^6, and the iterative O(n) solution was too slow for n=10^9, leading to CPU exhaustion.
Fix
Replaced the iterative solution with matrix exponentiation, reducing time complexity from O(n) to O(log n).
Key lesson
  • Always consider the worst-case input size when choosing an algorithm.
  • Recursive solutions can cause stack overflow for large n.
  • O(n) may be too slow for n > 10^7; use O(log n) when possible.
  • Test with extreme values before deploying to production.
  • Monitor CPU usage to detect inefficient algorithms early.
Production debug guideSymptom to Action4 entries
Symptom · 01
Incorrect results for large n but correct for small n
Fix
Check for integer overflow or modulo errors. Ensure matrix multiplication handles large numbers correctly.
Symptom · 02
Slow performance for large n
Fix
Verify that exponentiation uses binary exponentiation (log n steps). Check for unnecessary matrix copies.
Symptom · 03
Stack overflow or recursion depth error
Fix
Replace recursive exponentiation with iterative version. Use iterative matrix power.
Symptom · 04
Memory usage spikes
Fix
Ensure matrices are not being duplicated unnecessarily. Use in-place multiplication if possible.
★ Quick Debug Cheat SheetCommon issues and immediate fixes for matrix exponentiation.
Wrong answer for large n
Immediate action
Check modulo operation at each step
Commands
print(matrix_power(matrix, n))
print(matrix_multiply(A, B))
Fix now
Add modulo after each multiplication
Slow for n=10^9+
Immediate action
Check if exponentiation is O(log n)
Commands
time python script.py
print(n.bit_length())
Fix now
Implement binary exponentiation
Recursion depth error+
Immediate action
Switch to iterative exponentiation
Commands
sys.setrecursionlimit(1000000)
python -c 'print(1)'
Fix now
Use while loop instead of recursion
MethodTime ComplexitySpace ComplexitySuitable for
Iterative DPO(n)O(1)Small n (<10^7)
Matrix ExponentiationO(k^3 log n)O(k^2)Large n (up to 10^18)
Recursive with MemoizationO(n)O(n)Small n, but risk stack overflow
⚙ Quick Reference
7 commands from this guide
FileCommand / CodePurpose
fib_matrix_form.pyM = np.array([[1, 1], [1, 0]])Understanding Linear Recurrences and Their Matrix Form
matrix_exponentiation.pydef matrix_mult(A, B, mod=None):Matrix Multiplication and Exponentiation by Squaring
fib_matrix.pydef fib_matrix(n, mod=None):Implementing Fibonacci with Matrix Exponentiation
tribonacci.pydef tribonacci(n, mod=None):Generalizing to Arbitrary Linear Recurrences
optimized_mult.pydef matrix_mult_opt(A, B, mod):Performance Optimization and Modulo Arithmetic
common_mistakes.pydef fib_wrong(n):Common Pitfalls and How to Avoid Them
tiling.pydef tiling_ways(n, mod):Real-World Applications Beyond Fibonacci

Key takeaways

1
Matrix exponentiation reduces time for linear recurrences from O(n) to O(log n).
2
The companion matrix generalizes to any k-th order recurrence.
3
Always use modulo to keep numbers manageable and avoid overflow.
4
Test with small values to catch off-by-one errors.
5
Iterative exponentiation avoids stack overflow and is more efficient.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Implement a function to compute the n-th Fibonacci number using matrix e...
Q02SENIOR
How would you compute the n-th term of a linear recurrence of order k?
Q03SENIOR
Explain how to optimize matrix multiplication for large matrices in prod...
Q01 of 03SENIOR

Implement a function to compute the n-th Fibonacci number using matrix exponentiation.

ANSWER
Use the transformation matrix [[1,1],[1,0]] and exponentiation by squaring. Return M^(n-1)[0][0] for n>0.
FAQ · 3 QUESTIONS

Frequently Asked Questions

01
What is the time complexity of matrix exponentiation?
02
Can matrix exponentiation handle non-homogeneous recurrences?
03
Is matrix exponentiation always faster than dynamic programming?
N
Naren Founder & Principal Engineer

20+ years shipping performance-critical code where algorithms decide the bill. Written from production experience, not tutorials.

Follow
Verified
production tested
July 15, 2026
last updated
2,398
articles · all by Naren
🔥

That's Linear Algebra. Mark it forged?

3 min read · try the examples if you haven't

Previous
Singular Value Decomposition — SVD
6 / 8 · Linear Algebra
Next
Cholesky Decomposition: Efficient LDL^T Factorization for SPD Matrices