Exercise 7 of 30 · intermediate · loops · linearithmic · nested
A linear loop around a doubling loop
The code
for i in range(n):
j = 1
while j < n:
j *= 2
work()What is the total?
Count: work calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 24 |
| 16 | 64 |
| 32 | 160 |
| 64 | 384 |
| 128 | 896 |
| 256 | 2,048 |
| 512 | 4,608 |
| 1024 | 10,240 |
| 2048 | 22,528 |
| 4096 | 49,152 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n log n)
- Extra space
- O(1)
- Exact count
- n · ⌈log₂ n⌉
- The inner loop is independent of i and runs ⌈log₂ n⌉ times.
- It runs once per outer iteration: n · ⌈log₂ n⌉.
Common mistake: Adding instead of multiplying: n + log n. The inner loop is inside the outer one.
Check: measured count ÷ (n log n) settles near 1.00 for large n.