Exercise 5 of 30 · beginner · loops · logarithmic

Halving until one is left

The code

steps = 0
while n > 1:
    n = n // 2
    steps += 1

How many iterations for n = 1,000,000?

Count: halvings.

Measured counts

051020004000ncount
Measured
Table
ncount
83
164
325
646
1287
2568
5129
102410
204811
409612

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⌋
  1. After k iterations the value is about n / 2ᵏ.
  2. The loop stops when n / 2ᵏ < 2, i.e. after ⌊log₂ n⌋ iterations.
  3. 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.