Rare
0/9

# Matrix Exponentiation

Authors: Benjamin Qi, Harshini Rayasam, Neo Wang

Repeatedly multiplying a square matrix by itself.

### Prerequisites

Example - FibonacciProof by InductionImplementationProblems
Resources
CP2
CPH
CF

video + problemset

CF

interesting applications of mat exp

Mostafa

powerpoint of matrix exponentiation

## Example - Fibonacci

Focus Problem – try your best to solve this problem before continuing!

The fibonacci numbers are defined by the following matrix relation

$A = \begin{bmatrix}1&1\\1&0\end{bmatrix}^n=\begin{bmatrix}F_{n+1} & F_n \\ F_n & F_{n-1}\end{bmatrix}$

### Proof by Induction

The fibonacci numbers are defined as follows:

\begin{align*} F_0 &= 0 \\ F_1 &= 1 \\ F_{n+1} &= F_{n} + F_{n-1} \end{align*}

Base case ($n=1$):

$A^1 = \begin{bmatrix}1 & 1 \\ 1 & 0\end{bmatrix} = \begin{bmatrix}F_2 & F_1 \\ F_1 & F_0\end{bmatrix}$

Induction step ($n+1$):

$A^{n+1}=A\,A^n=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}\begin{bmatrix} F_{n+1} & F_{n} \\ F_{n} & F_{n-1} \end{bmatrix}=\begin{bmatrix} F_{n+1}+F_n & F_{n}+F_{n-1} \\ F_{n+1} & F_{n} \end{bmatrix}=\begin{bmatrix} F_{n+2} & F_{n+1} \\ F_{n+1} & F_{n} \end{bmatrix}$

The base case is true, and the induction step is true. Therefore the formula holds for all $n \in \mathbb{N}$.

C++

## Implementation

Time complexity: $\mathcal{O}(\log n)$

#include <bits/stdc++.h>using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
using Matrix = array<array<ll, 2>, 2>;
Matrix mul(Matrix a, Matrix b) {

Python

from typing import List
MOD = 10**9 + 7

def mul(A: List[List[int]], B: List[List[int]], MOD: int) -> List[List[int]]:	C = [[0, 0], [0, 0]]	for i in range(2):		for j in range(2):			for k in range(2):

## Problems

StatusSourceProblem NameDifficultyTags
CSESEasy
Show TagsExponentiation, Matrix
CSESEasy
Show TagsExponentiation, Matrix
CFEasy
Show TagsExponentiation, Matrix
CFNormal
Show TagsExponentiation, Matrix, PURS
Baltic OINormal
Show TagsExponentiation, Matrix
Balkan OINormal
Show TagsExponentiation, Matrix
DMOJNormal
Show TagsExponentiation, Matrix
PlatHard
Show TagsExponentiation, Matrix

### Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!