Exercise 5 of 30 · beginner · loops · logarithmic
Halving until one is left
The code
steps = 0
while n > 1:
n = n // 2
steps += 1How many iterations for n = 1,000,000?
Count: halvings.
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⌋
- After k iterations the value is about n / 2ᵏ.
- The loop stops when n / 2ᵏ < 2, i.e. after ⌊log₂ n⌋ iterations.
- For one million: ⌊log₂ 1,000,000⌋ = 19.
Common mistake: Answering n/2. Halving repeatedly is logarithmic; subtracting 2 each time would be linear.
Check: measured count ÷ (log n) settles near 1.00 for large n.