Sub topic 2
Nested Loops: Multiplying Costs
This chapter assumes you can count the iterations of a single loop from its bounds and step size. You should also be comfortable with exponents and logarithms.
Independent Nested Loops
A nested loop is independent when the inner loop's bounds do not use the outer loop's variable. In that case the inner body runs m times for each of the n outer iterations, so the total is n * m.
def count_grid(n, m):
steps = 0
for i in range(n):
for j in range(m):
steps += 1
return steps
print(count_grid(4, 5)) # 20A common error is to add the two counts (n + m) instead of multiplying them. You add costs only when the blocks run one after another.
Series You Need
Two series cover most loop counting:
| Series | Closed form | Growth |
|---|---|---|
| 0 + 1 + 2 + ... + (n-1) | n(n-1)/2 | Theta(n^2) |
| 1 + 2 + 4 + ... + 2^k | 2^(k+1) - 1 | Theta(2^k) |
The arithmetic series appears when an inner bound shrinks by one on each outer pass. The geometric series appears when the work doubles or halves on each pass.
Triangular Loops and Dependent Bounds
When the inner loop starts at i + 1, it runs n-1, then n-2, and so on down to 0 times. The arithmetic series gives the total.
def count_pairs(n):
steps = 0
for i in range(n):
for j in range(i + 1, n):
steps += 1
return steps
for n in (5, 10, 100):
assert count_pairs(n) == n * (n - 1) // 2
print(count_pairs(10)) # 45The count is about half of n * n, but it is still Theta(n^2). Skipping half the pairs saves a constant factor and leaves the order of growth unchanged.
Loops That Halve or Double
If a loop divides its control variable by 2 on each pass, the number of passes is about the number of times you can halve n before it reaches 0. For n >= 1, that is floor(log2 n) + 1.
def count_halving(n):
steps = 0
while n > 0:
n //= 2
steps += 1
return steps
for n in (1, 8, 1000):
assert count_halving(n) == n.bit_length()
print(count_halving(1000)) # 10A loop that doubles a variable from 1 up to n also runs Theta(log n) times. If the variable is multiplied by any constant greater than 1 on each pass, the count stays logarithmic. Only the base of the log changes, and the base is a constant factor.
Exercise
How many times does the inner body run in for i in range(n): for j in range(i): ..., and what is its order of growth?
Show answer
The inner loop runs 0 + 1 + ... + (n-1) = n(n-1)/2 times, which is Theta(n^2).
Exercise
A loop starts with k = 1 and runs while k < n: k *= 3. Roughly how many iterations does it make?
Show answer
About ceil(log3 n) iterations, which is Theta(log n).