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

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. i takes the values 1, 2, 4, …, 2ᵏ.
  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.