Sub topic 9
Mixing Linear and Logarithmic Loops
This chapter assumes you can already count a single loop from its bounds and step size. It also assumes you can multiply the costs of independent nested loops and count a halving loop as floor(log2 n) + 1 iterations. You should also be comfortable summing a geometric series. Here we combine those skills. The goal is to predict the cost when one loop changes its control variable by a fixed amount each time and another loop halves or doubles its variable.
The combined count is not always n log n. A linear loop nested with a logarithmic loop can produce Θ(n log n), Θ(n), or Θ(log² n). The result depends on which loop is outside and on whether the inner bound depends on the outer variable. Most mistakes in this area come from multiplying the two counts when the bounds are actually dependent.
The Independent Case: Multiply
When neither loop's bounds depend on the other loop's variable, the rule from independent nested loops still applies. Multiply the outer count by the inner count.
Linear outside, logarithmic inside
def count_linear_log(n):
steps = 0
for i in range(n): # n iterations
j = n
while j > 0: # n.bit_length() iterations, every time
j //= 2
steps += 1
return steps
for n in (1, 8, 1000):
assert count_linear_log(n) == n * n.bit_length()
print(count_linear_log(1000)) # 10000The inner loop always starts at n, so it runs floor(log2 n) + 1 times on every pass. There are n passes. The exact count is n * (floor(log2 n) + 1), which is Θ(n log n).
Logarithmic outside, linear inside
Swapping the roles gives the same count, because multiplication is commutative:
def count_log_linear(n):
steps = 0
k = n
while k > 0: # n.bit_length() iterations
for j in range(n): # n iterations, every time
steps += 1
k //= 2
return steps
for n in (1, 8, 1000):
assert count_log_linear(n) == n * n.bit_length()
print(count_log_linear(1000)) # 10000The inner loop reads range(n), not range(k). The outer variable k only controls how many times the inner loop is repeated. It never changes how long each repetition is. This detail separates this example from the next one.
The Dependent Case: Sum, Don't Multiply
If the inner bound uses the outer variable, each pass of the outer loop costs a different amount. You have to add up the cost of each pass. Multiplying the largest inner count by the number of passes gives only an upper bound, and that bound can be loose by a whole factor of log n.
Shrinking linear work inside a halving loop
def count_shrinking(n):
steps = 0
k = n
while k > 0:
for j in range(k): # k iterations, and k keeps halving
steps += 1
k //= 2
return steps
for n in (1, 8, 1000, 10**6):
assert count_shrinking(n) < 2 * n
print(count_shrinking(1000)) # 1994The inner loop runs n, then n//2, then n//4, and so on down to 1. For n = 1000 the passes cost 1000, 500, 250, 125, 62, 31, 15, 7, 3, and 1, for a total of 1994. This is a geometric series with ratio 1/2:
n + n/2 + n/4 + ... < n · (1 + 1/2 + 1/4 + ...) = 2n
The loop structure looks like "log n passes of up to n work." The total is still below 2n, so the cost is Θ(n), not Θ(n log n). The first pass alone costs n, and that gives the matching lower bound.
Growing linear work inside a doubling loop
The doubling version gives the same result. Here the series grows toward its largest term instead of shrinking away from it:
def count_doubling_inner(n):
steps = 0
i = 1
while i < n:
for j in range(i): # i iterations: 1, 2, 4, 8, ...
steps += 1
i *= 2
return steps
for n in (2, 8, 1000, 10**6):
assert count_doubling_inner(n) < 2 * n
print(count_doubling_inner(1000)) # 1023For n = 1000, i takes the values 1, 2, 4, ..., 512. Their sum is 2^10 - 1 = 1023. In general, a geometric series with ratio 2 sums to less than twice its last term, and the last term is below n. So the total is below 2n, which is Θ(n). In geometric sums, the biggest term sets the order of growth.
Logarithmic work inside a linear loop, with a dependent bound
Now put the dependency in the other direction. The outer loop is linear, and the inner halving loop starts from the outer variable:
def count_dependent_halving(n):
steps = 0
for i in range(1, n + 1):
j = i
while j > 0: # i.bit_length() iterations
j //= 2
steps += 1
return steps
for n in (1, 8, 1000):
assert count_dependent_halving(n) == sum(i.bit_length() for i in range(1, n + 1))
print(count_dependent_halving(1000)) # 8987The exact count is the sum of floor(log2 i) + 1 for i from 1 to n. For n = 1000 that is 8987, a little under the 10000 from the independent version. Shrinking the inner bound did not change the order of growth this time. The reason comes from bounding the sum from both sides:
- Upper bound: every term is at most
log2 n + 1, so the sum is at mostn(log2 n + 1), which is O(n log n). - Lower bound: the top half of the values,
ifromn/2ton, each cost at leastlog2(n/2) = log2 n - 1. That gives at least(n/2)(log2 n - 1), which is Ω(n log n).
The two bounds have the same order, so the cost is Θ(n log n). The sum also equals roughly log2(n!). Stirling's approximation gives the same order for that.
The two dependent cases come out differently because of how the terms are spread out. In a geometric series one term dominates and the rest add only a constant factor. In a sum of logarithms the terms are nearly equal, because log i changes very slowly. Most terms are close to the largest one, so the total behaves like n times the largest term.
Both Loops Logarithmic
When two independent halving loops are nested, the product of their counts is Θ(log² n):
def count_log_log(n):
steps = 0
i = n
while i > 0:
j = n
while j > 0:
j //= 2
steps += 1
i //= 2
return steps
for n in (1, 8, 1000):
assert count_log_log(n) == n.bit_length() ** 2
print(count_log_log(1000)) # 100If the inner loop instead starts at j = i, the counts become L, L-1, ..., 1, where L = n.bit_length(). That is an arithmetic series summing to L(L+1)/2, which is still Θ(log² n). The dependency halves the count without changing its order.
Sequential Mixing: Add, Then Keep the Largest
Loops that run one after another, rather than nested, add their costs:
def count_sequential(n):
steps = 0
for i in range(n): # n
steps += 1
k = n
while k > 0: # n.bit_length()
k //= 2
steps += 1
return steps
for n in (1, 8, 1000):
assert count_sequential(n) == n + n.bit_length()
print(count_sequential(1000)) # 1010n + log n is Θ(n). The logarithmic block makes up less than 1% of the work at n = 1000, and its share keeps shrinking as n grows.
A Decision Procedure
The table collects the patterns from this chapter.
| Structure | Per-pass cost | Exact count (n = 1000) | Order |
|---|---|---|---|
| `for i in range(n)` / inner halves from `n` | `log n`, constant | 10000 | Θ(n log n) |
| outer halves `k` / inner `range(n)` | `n`, constant | 10000 | Θ(n log n) |
| outer halves `k` / inner `range(k)` | `n, n/2, n/4, ...` | 1994 | Θ(n) |
| outer doubles `i` / inner `range(i)` | `1, 2, 4, ...` | 1023 | Θ(n) |
| `for i in 1..n` / inner halves from `i` | `log i` | 8987 | Θ(n log n) |
| halving inside halving, both from `n` | `log n`, constant | 100 | Θ(log² n) |
| linear loop, then halving loop | n/a (sequential) | 1010 | Θ(n) |
Edge Cases Worth Checking
- Small or zero
n. Forn = 0,range(0)andwhile k > 0both run zero times, so every function above returns 0. The formulan * n.bit_length()also gives 0. Check formulas at the boundaries, because "log n" is undefined at 0 even though the code is fine. < nversus<= nin doubling loops.while i < nwithistarting at 1 runsceil(log2 n)times forn >= 1.while i <= nrunsfloor(log2 n) + 1times. The order of growth is the same, but exact counts differ by one whennis a power of two.- Halving that never reaches zero.
while k > 0: k /= 2uses float division.kshrinks until it underflows to 0.0, which takes about 1075 iterations forkstarting at 1000. That count does not depend onnin any useful way. Use//when you mean integer halving. - The base of the logarithm. Dividing by 3 instead of 2 gives
log3 npasses. Bases differ only by a constant factor, so Θ(n log n) stays the same. Exact counts do not.
Exercise
What is the order of growth of steps in this code, and why? steps = 0; i = 1 then while i < n: containing for j in range(i, n): steps += 1 followed by i *= 2.
Show answer
The pass with value i costs n - i, and i takes the values 1, 2, 4, ... below n. That is about log2 n passes. Subtracting the geometric sum 1 + 2 + 4 + ... (less than 2n) from n·log2 n leaves at least n·log2 n - 2n, so the cost is Θ(n log n). Most passes have small i and cost close to n, which makes this the slowly-varying case.
Exercise
A function sorts a list of length n with an O(n log n) sort, then runs a binary search (a halving loop) on the result once for each of n queries. What is the total order of growth?
Show answer
Θ(n log n). The sort costs O(n log n). The n binary searches each cost O(log n), for O(n log n) in total. The sum of two Θ(n log n) blocks run in sequence is still Θ(n log n).
Exercise
Predict count_shrinking(16) exactly, then explain why the result does not grow like 16 · log2 16 = 64.
Show answer
The passes cost 16, 8, 4, 2, and 1, for a total of 31. The inner bound halves on every pass, so the costs form a geometric series bounded by 2n = 32. Multiplying the number of passes by the largest pass overcounts by a factor of about log n.