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 be a semiring with a multiplicative unit (for example a ring), and let the matrix product over be associative, with identity . For write for the product of copies of ; by associativity, for all , and .
Claim. For every and every integer , MATRIX-EXPONENTIATION stops and returns . For it makes exactly matrix products, where is the number of ones in the binary form of .
Case . Line L1 returns and makes no product.
Case . Let with and , so . For let
Then , , and for , because shifting the digits one place left and appending gives the digits .
Invariant. At the start of the iteration of line L4 with index , .
Initialization. Before the first iteration, and line L3 set .
Maintenance. Assume at the start of iteration . Line L5 sets to . If , line L6 sets to . In both cases , which is the invariant for the next index .
Termination. The loop runs for , that is iterations, and drops by exactly one each time, so it stops. After the last iteration (), the invariant for the index gives , which line L7 returns. If (so ), the loop does not run and .
Count. Line L5 runs once in each of the iterations. Line L6 makes a product exactly for the indices with ; there are of them, since is the only digit that the loop does not see. So the total is .
Remark. Each product in lines L5 and L6 must be written to fresh storage. The proof treats as the assignment of the value , which needs the old until the product is complete.