Proofs: Naive matrix multiplication
These are the human proofs of Naive matrix multiplication, at full length.
The triple loop computes the matrix product full
This proof shows: correctness, termination.
Let be a ring, or more generally a semiring: a set with an associative addition that has a neutral element , and a multiplication. Commutativity of the multiplication is not used. Let be an matrix and an matrix over , with .
Claim. MATRIX-MULTIPLY stops, and it returns the matrix with for all and . The sum is taken in the order , and it is when .
Termination. Each of the three loops of lines L2, L3 and L5 runs over a fixed finite range, and the body changes none of the loop variables. So line L6 runs exactly times and the procedure stops.
Step 1 (the inner loop). Fix and . We show that each time the test of line L5 runs with the value , this invariant holds:
(S) .
Initialization. Line L4 sets and the first test has . The sum over the empty range is , so (S) holds.
Maintenance. Assume (S) holds for . Line L6 sets to , by associativity of addition. The next test has the value , so (S) holds again.
Termination. The loop exits at the test with . By (S), , which is the claimed value of .
Step 2 (the outer loops). Line L7 then writes this value into . Lines L2 and L3 run the body once for each pair with and , and line L7 for the pair is the only write to . The computation of the pair reads only and , which the procedure never writes, and is a new matrix that shares no memory with them. So no later step changes , and after the loops each entry has its claimed value. Line L8 returns .
Remark (loop orders). In any of the six orders of the three loops, with set to at the start and the update as the body, the triples with fixed are visited in increasing order of in the orders , , , , and , since is either the inner loop or an outer loop. So the same argument, applied to each fixed , shows that all six orders return the same matrix, even when addition is not commutative.