Sub topic 9
Mixing Linear and Logarithmic Loops
This chapter assumes you can count a single loop, multiply the costs of independent nested loops, count a halving loop as floor(log2 n) + 1 iterations, and sum a geometric series. Here we combine those skills. A linear loop and a logarithmic loop can nest in three common ways, and they do not all give the same answer.
Pattern 1: Linear Outside, Logarithmic Inside
If the inner loop's bounds do not depend on the outer variable, the multiplication rule still applies. The outer loop runs n times. Each time, the inner loop halves a fresh copy of n down to 0.
def count_linear_log(n):
steps = 0
for i in range(n):
j = n
while j > 0:
j //= 2
steps += 1
return steps
for n in (1, 16, 1000):
assert count_linear_log(n) == n * n.bit_length()
print(count_linear_log(1000)) # 10000The total is n * (floor(log2 n) + 1), which is Θ(n log n). If you swap the two loops, so that a halving loop runs on the outside and a full range(n) loop runs on the inside, the product is the same, as long as the inner loop always runs to n.
Pattern 2: Halving Outside, Inner Loop Shrinks With It
The answer changes when the inner loop's length depends on the halving variable.
def count_shrinking(n):
steps = 0
i = n
while i > 0:
for j in range(i):
steps += 1
i //= 2
return steps
for n in (1, 7, 1000, 10**5):
assert count_shrinking(n) < 2 * n
print(count_shrinking(1000)) # 1994The outer loop runs about log2 n times. Multiplying gives n log n, but that bound is loose. The inner loop runs n, then n/2, then n/4, and so on. That is a geometric series:
n + n/2 + n/4 + ... < n * (1 + 1/2 + 1/4 + ...) = 2n
So the total is Θ(n). The first pass does about half of all the work, and each later pass adds only half as much as the one before it.
Pattern 3: Linear Outside, Doubling Inside Up to `i`
Here the inner loop doubles j until it passes the outer variable i.
def count_doubling_inner(n):
steps = 0
for i in range(1, n + 1):
j = 1
while j <= i:
j *= 2
steps += 1
return steps
for n in (1, 10, 1000):
assert count_doubling_inner(n) == sum(i.bit_length() for i in range(1, n + 1))
print(count_doubling_inner(1000)) # 8987For each i, the inner loop runs floor(log2 i) + 1 times. The total is the sum of log2 i for i from 1 to n. Every term is at most log2 n, so the sum is at most n log2 n + n. The top half of the terms, where i ≥ n/2, are each at least log2 n - 1. That gives a lower bound of about (n/2)(log2 n - 1). The upper and lower bounds have the same order, so the total is Θ(n log n). The inner bound depends on i here, but it grows slowly enough that the answer matches Pattern 1.
Summary of the Patterns
| Outer loop | Inner loop | Exact or bounded count | Order |
|---|---|---|---|
| `range(n)` | halve `n` to 0 | `n * (floor(log2 n) + 1)` | Θ(n log n) |
| halve `i` from `n` | `range(i)` | `< 2n` | Θ(n) |
| `range(1, n+1)` | double `j` while `j <= i` | sum of `floor(log2 i) + 1` | Θ(n log n) |
Common Errors
- Assuming that any loop nested around a halving loop must be n log n. Check which variable the inner loop actually uses.
- Counting the outer halving loop as log n iterations and stopping there. You also have to add up the cost of each iteration.
- Forgetting that a doubling loop starting at
j = 1runs once even wheni = 1.
Exercise
What is the order of growth of this function, and roughly what does it return for n = 1024? def f(n): steps = 0 i = 1 while i < n: for j in range(i): steps += 1 i *= 2 return steps
Show answer
The inner loop runs i = 1, 2, 4, ..., 512 times for n = 1024. That geometric series sums to 1023, so f(1024) returns 1023. In general the total is less than n, and it is at least n/2, so it is Θ(n). The largest term is the main contributor, as in Pattern 2.
Exercise
Change Pattern 1 so the inner loop starts with j = i instead of j = n, and the outer loop is range(1, n + 1). What is the order of growth now?
Show answer
The inner loop now runs floor(log2 i) + 1 times, so the total is the sum of i.bit_length() for i from 1 to n. By the same argument as Pattern 3, that sum is Θ(n log n).