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

020k40k20004000ncount
Measured
Table
ncount
824
1664
32160
64384
128896
2562,048
5124,608
102410,240
204822,528
409649,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⌉
  1. The inner loop is independent of i and runs ⌈log₂ n⌉ times.
  2. 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.