Algorithm Search⌘K

Proofs: Matrix exponentiation

These are the human proofs of Matrix exponentiation, at full length.

The left-to-right binary method computes A^k full

This proof shows: correctness, termination.

Let SS be a semiring with a multiplicative unit (for example a ring), and let the matrix product over SS be associative, with identity InI_n. For q≥1q \ge 1 write AqA^q for the product of qq copies of AA; by associativity, AqAr=Aq+rA^{q} A^{r} = A^{q + r} for all q,r≥1q, r \ge 1, and A0=InA^0 = I_n.

Claim. For every A∈Sn×nA \in S^{n \times n} and every integer k≥0k \ge 0, MATRIX-EXPONENTIATION(A,k)(A, k) stops and returns AkA^k. For k≥1k \ge 1 it makes exactly ⌊lg⁡k⌋+ν(k)−1\lfloor \lg k \rfloor + \nu(k) - 1 matrix products, where ν(k)\nu(k) is the number of ones in the binary form of kk.

Case k=0k = 0. Line L1 returns In=A0I_n = A^0 and makes no product.

Case k≥1k \ge 1. Let k=∑i=0tbi2ik = \sum_{i=0}^{t} b_i 2^i with bi∈{0,1}b_i \in \{0, 1\} and bt=1b_t = 1, so t=⌊lg⁡k⌋t = \lfloor \lg k \rfloor. For −1≤i≤t−1-1 \le i \le t - 1 let

qi=⌊k2i+1⌋=∑j=i+1tbj2j−i−1.q_i = \left\lfloor \frac{k}{2^{i+1}} \right\rfloor = \sum_{j=i+1}^{t} b_j 2^{j-i-1}.

Then qt−1=bt=1q_{t-1} = b_t = 1, q−1=kq_{-1} = k, and qi−1=2qi+biq_{i-1} = 2 q_i + b_i for 0≤i≤t−10 \le i \le t - 1, because shifting the digits bt…bi+1b_t \ldots b_{i+1} one place left and appending bib_i gives the digits bt…bib_t \ldots b_i.

Invariant. At the start of the iteration of line L4 with index ii, R=AqiR = A^{q_i}.

Initialization. Before the first iteration, i=t−1i = t - 1 and line L3 set R=A=A1=Aqt−1R = A = A^{1} = A^{q_{t-1}}.

Maintenance. Assume R=AqiR = A^{q_i} at the start of iteration ii. Line L5 sets RR to AqiAqi=A2qiA^{q_i} A^{q_i} = A^{2 q_i}. If bi=1b_i = 1, line L6 sets RR to A2qiA=A2qi+1A^{2 q_i} A = A^{2 q_i + 1}. In both cases R=A2qi+bi=Aqi−1R = A^{2 q_i + b_i} = A^{q_{i-1}}, which is the invariant for the next index i−1i - 1.

Termination. The loop runs for i=t−1,t−2,…,0i = t - 1, t - 2, \ldots, 0, that is tt iterations, and ii drops by exactly one each time, so it stops. After the last iteration (i=0i = 0), the invariant for the index −1-1 gives R=Aq−1=AkR = A^{q_{-1}} = A^k, which line L7 returns. If t=0t = 0 (so k=1k = 1), the loop does not run and R=A=A1R = A = A^1.

Count. Line L5 runs once in each of the tt iterations. Line L6 makes a product exactly for the indices i≤t−1i \le t - 1 with bi=1b_i = 1; there are ν(k)−1\nu(k) - 1 of them, since bt=1b_t = 1 is the only digit 11 that the loop does not see. So the total is t+ν(k)−1=⌊lg⁡k⌋+ν(k)−1t + \nu(k) - 1 = \lfloor \lg k \rfloor + \nu(k) - 1. ■\blacksquare

Remark. Each product in lines L5 and L6 must be written to fresh storage. The proof treats R←R⋅RR \leftarrow R \cdot R as the assignment of the value R⋅RR \cdot R, which needs the old RR until the product is complete.

Back to Matrix exponentiation