Exercise 8 of 30 · intermediate · loops · geometric series · linear

Inner loop bounded by a halving outer variable

The code

i = n
while i > 0:
    for j in range(i):
        work()
    i = i // 2

Two nested loops: is it Θ(n log n) or Θ(n²)?

Count: work calls.

Measured counts

0500020004000ncount
Measured
Table
ncount
815
1631
3263
64127
128255
256511
5121,023
10242,047
20484,095
40968,191

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(n)
Extra space
O(1)
Exact count
n + ⌊n/2⌋ + ⌊n/4⌋ + … < 2n
  1. The inner loop runs i times, and i halves each round.
  2. Total: n + n/2 + n/4 + … — a geometric series bounded by 2n.
  3. So the whole thing is Θ(n), even though the loops are nested.

Common mistake: Multiplying the two loop counts (n · log n). Nested loops multiply only when the inner count does not depend on the outer variable.

Check: measured count ÷ (n) settles near 2.00 for large n.