Exercise 8 of 30 · intermediate · loops · geometric series · linear
Inner loop bounded by a halving outer variable
The code
i = n
while i > 0:
for j in range(i):
work()
i = i // 2Two nested loops: is it Θ(n log n) or Θ(n²)?
Count: work calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 15 |
| 16 | 31 |
| 32 | 63 |
| 64 | 127 |
| 128 | 255 |
| 256 | 511 |
| 512 | 1,023 |
| 1024 | 2,047 |
| 2048 | 4,095 |
| 4096 | 8,191 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n)
- Extra space
- O(1)
- Exact count
- n + ⌊n/2⌋ + ⌊n/4⌋ + … < 2n
- The inner loop runs i times, and i halves each round.
- Total: n + n/2 + n/4 + … — a geometric series bounded by 2n.
- So the whole thing is Θ(n), even though the loops are nested.
Common mistake: Multiplying the two loop counts (n · log n). Nested loops multiply only when the inner count does not depend on the outer variable.
Check: measured count ÷ (n) settles near 2.00 for large n.