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
Table
| n | count |
|---|---|
| 8 | 512 |
| 16 | 4,096 |
| 32 | 32,768 |
| 64 | 262,144 |
| 128 | 2,097,152 |
| 256 | 16,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³
- Three independent loops of n iterations each multiply: n³.
- 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.