Exercise 11 of 30 · beginner · loops · cubic · matrix multiplication

Three nested loops

The code

for i in range(n):
    for j in range(n):
        for k in range(n):
            C[i][j] += A[i][k] * B[k][j]

What does naive n×n matrix multiplication cost?

Count: multiply-adds.

Measured counts

05.0M10M15M100200ncount
Measured
Table
ncount
8512
164,096
3232,768
64262,144
1282,097,152
25616,777,216

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(n³)
Extra space
Θ(n²) for the result
Exact count
n³
  1. Three independent loops of n iterations each multiply: n³.
  2. The output C has n² cells: Θ(n²) space.

Common mistake: Confusing time with space: the result holds n² numbers, but computing each takes n steps.

Check: measured count ÷ (n³) settles near 1.00 for large n.