Exercise 6 of 30 · beginner · loops · logarithmic
Doubling a counter
The code
i = 1
while i < n:
i = i * 2
work()How does the number of iterations grow?
Count: work calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 3 |
| 16 | 4 |
| 32 | 5 |
| 64 | 6 |
| 128 | 7 |
| 256 | 8 |
| 512 | 9 |
| 1024 | 10 |
| 2048 | 11 |
| 4096 | 12 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(log n)
- Extra space
- O(1)
- Exact count
- ⌈log₂ n⌉
- i takes the values 1, 2, 4, …, 2ᵏ.
- The loop runs while 2ᵏ < n: k = ⌈log₂ n⌉ times.
Common mistake: Treating any while loop that "goes up to n" as linear. What matters is how fast the variable moves.
Check: measured count ÷ (log n) settles near 1.00 for large n.