Sub topic 8
Loops That Halve or Double
This chapter assumes you can read Python while loops, count the iterations of a loop from its bounds, and know that log2 n is the power you raise 2 to in order to get n. Earlier chapters covered loops whose control variable changes by addition, such as i += 1 or i += s. Here the control variable changes by multiplication or division. That one change takes the iteration count from linear to logarithmic. For large inputs, a logarithmic loop does very little work.
The Halving Loop
Here is the basic pattern. Each iteration divides n by 2 and drops the remainder, until nothing is left.
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)) # 10The body takes constant time, so the cost of the loop is the number of iterations. To find that number, trace a concrete input. Start with n = 37.
| Iteration | n before | n after `n //= 2` |
|---|---|---|
| 1 | 37 | 18 |
| 2 | 18 | 9 |
| 3 | 9 | 4 |
| 4 | 4 | 2 |
| 5 | 2 | 1 |
| 6 | 1 | 0 |
The loop runs 6 times. 37 lies between 2^5 = 32 and 2^6 = 64, and 6 is the number of bits in its binary form, 100101. That fits what the loop does: n //= 2 is a right shift by one bit, so the loop strips one bit per iteration until no bits are left.
Deriving the count
Tracing works for one input. A formula covers every input. After k iterations, the variable holds floor(n / 2^k). The loop keeps going while that value is positive, which means while 2^k ≤ n. So it stops at the first k with 2^k > n:
- The last iteration that runs is the largest k with 2^(k-1) ≤ n, which is k − 1 = floor(log2 n).
- The total count for n ≥ 1 is floor(log2 n) + 1.
- For n = 0 the loop does not run at all.
Python's int.bit_length() returns exactly this value for any non-negative integer, so you can check your formula against it.
Small changes to the condition shift the count by one
The loop condition and the starting value control the exact count. The order of growth stays the same. Each version below is Θ(log n), but they differ by one iteration, and that difference matters when you predict a counter's value.
| Loop | Iterations for n ≥ 1 | n = 8 | n = 9 |
|---|---|---|---|
| `while n > 0: n //= 2` | floor(log2 n) + 1 | 4 | 4 |
| `while n > 1: n //= 2` | floor(log2 n) | 3 | 3 |
| `i = 1; while i < n: i *= 2` | ceil(log2 n) | 3 | 4 |
| `i = 1; while i <= n: i *= 2` | floor(log2 n) + 1 | 4 | 4 |
The Doubling Loop
A doubling loop runs the halving process in reverse. Rather than shrinking n toward 0, it grows a variable from 1 up to n.
def count_doubling(n):
steps = 0
i = 1
while i < n:
i *= 2
steps += 1
return steps
for n in range(1, 2000):
assert count_doubling(n) == (n - 1).bit_length()
print(count_doubling(8), count_doubling(9)) # 3 4After k iterations, i = 2^k. The loop stops at the first k with 2^k ≥ n, which is k = ceil(log2 n). The check uses (n - 1).bit_length() because ceil(log2 n) equals the bit length of n − 1 for n ≥ 1. The loop in the code visits 1, 2, 4, 8, … and makes only about log2 n stops between 1 and n.
Why the Base Does Not Change the Order of Growth
Some loops divide by 3, 10, or another constant k instead of 2:
def count_digits(n, base):
steps = 0
while n > 0:
n //= base
steps += 1
return steps
print(count_digits(1000, 10)) # 4
print(count_digits(1000, 3)) # 7
print(count_digits(1000, 2)) # 10This loop counts the digits of n in the given base, which is floor(logk n) + 1. The change-of-base rule says logk n = log2 n / log2 k. Since log2 k is a fixed number, every base gives the same growth rate up to a constant factor. That is why complexity notation writes O(log n) with no base. Dividing by 10 instead of 2 cuts the work by a factor of about 3.3, and the growth rate is still logarithmic.
The divisor has to be a constant greater than 1 for this to hold. Dividing by 1 never shrinks n, so the loop never ends. A divisor that changes from one iteration to the next has to be analyzed separately, as described later in this chapter.
How Small log n Really Is
A logarithmic loop grows extremely slowly. Each time n doubles, the loop gains one iteration, while a linear loop doubles its work.
| n | Linear loop iterations | Halving loop iterations |
|---|---|---|
| 16 | 16 | 5 |
| 1,024 | 1,024 | 11 |
| 1,048,576 | 1,048,576 | 21 |
| 10^9 | 1,000,000,000 | 30 |
| 10^18 | 10^18 | 60 |
Spotting the Pattern in Real Code
Variables named n and i make the pattern easy to see. In real code you need a more general test: does each iteration multiply the remaining work by a constant fraction? If so, the loop is logarithmic in the starting size. Common examples:
- Shrinking intervals. Binary search sets
lo = mid + 1orhi = mid - 1, which removes about half of the interval each time. - Digit processing.
while x: d = x % 10; x //= 10runs once per decimal digit. - Exponentiation by squaring. The exponent is halved on each iteration.
- Floating-point convergence.
while width > eps: width /= 2runs about log2(width0 / eps) times. The count depends on the ratio between the starting width and the tolerance, and it does not depend on any n.
Here is a halving loop on an interval, written so the iterations can be counted:
def bisect_steps(lo, hi):
"""Count halvings until the integer interval [lo, hi] has one value."""
steps = 0
while hi > lo:
mid = (lo + hi) // 2
hi = mid # keep the lower half
steps += 1
return steps
print(bisect_steps(0, 1023)) # 10, since the interval holds 1024 values
print(bisect_steps(0, 999)) # 10, ceil(log2 1000)The interval size goes from s to ceil(s/2), so the count is ceil(log2 s) for an interval of s values. The loop never names n, i *= 2, or //= 2 as a counter step. You find the logarithm by following what happens to hi - lo + 1.
Lookalikes that are not logarithmic
Some loops look like they halve but do not. A few short traces will expose them.
| Loop | What happens | Iterations |
|---|---|---|
| `while n > 0: n -= 2` | subtracts a constant | about n/2, so Θ(n) |
| `while n > 0: n = n - n // 2 ... ` with `n` stuck at 1 | 1 - 0 = 1, never reaches 0 | infinite |
| `i = 2; while i < n: i = i * i` | squares: 2, 4, 16, 256, … | Θ(log log n) |
| `while n > 1: n = n // 2 + 1` | stops shrinking at n = 2 | infinite for n ≥ 2 |
The squaring loop is worth noticing. After k iterations i = 2^(2^k), so it reaches n after about log2(log2 n) iterations. That is even fewer than a halving loop needs. Multiplying by a constant gives a logarithm, and squaring gives a logarithm of a logarithm.
A Gotcha: Computing the Count with Floats
You may want to predict the count with int(math.log2(n)) + 1. For small n that works. For large integers it can be off by one, because converting to a float rounds the value.
import math
n = 2**60 - 1
print(int(math.log2(n)) + 1) # 61, wrong: the float rounds n up to 2**60
print(n.bit_length()) # 60, correct
print(math.log2(n)) # 60.02**60 - 1 has 60 bits, but the nearest float is exactly 2^60, so math.log2 returns 60.0 and the formula adds a phantom iteration. For exact counts on integers, use bit_length() or integer arithmetic. Use math.log2 to estimate magnitude, not to check a count exactly.
Summary of the Method
- Find the quantity that controls the loop: the variable itself, an interval width, or the number of remaining items.
- Write the value after k iterations, such as n / 2^k or 2^k.
- Set that expression equal to the exit condition and solve for k. The solution involves log.
- Fix the exact count by tracing a power of 2 and a value next to it.
- Check for termination: zero, negative, and fixed-point values that can trap the loop.
Exercise
How many times does this loop run for n = 100, and what is the general formula for n ≥ 1? i = 1 while i <= n: i *= 3
Show answer
i takes the values 1, 3, 9, 27, 81 while i ≤ 100, then becomes 243 and the loop exits, so it runs 5 times. In general it runs once for each power 3^k ≤ n with k from 0 to floor(log3 n), which is floor(log3 n) + 1 times, or Θ(log n).
Exercise
Is this loop Θ(log n), Θ(n), or something else? x = n; while x > 0: x -= max(1, x // 2)
Show answer
Θ(log n). For x ≥ 2 each iteration removes floor(x/2), which leaves ceil(x/2). That halves x, rounding up. Once x is 1, it subtracts 1 and stops. The count is about log2 n + 1. The max(1, …) term only matters in the last step, and it ensures the loop ends.
Exercise
A loop runs while width > 1e-6 and starts at width = 1.0, with width /= 2 in the body. About how many iterations does it run, and why does the count not depend on any input size n?
Show answer
It runs until 2^k ≥ 10^6, so k = ceil(log2 10^6) = 20 iterations. The count depends only on the ratio of the starting width to the tolerance, which is log2(1.0 / 1e-6). If both values are fixed constants, the loop costs O(1). It grows logarithmically only if the precision you require grows.
Exercise
Why does int(math.log2(n)) + 1 sometimes disagree with count_halving(n) for large n, and what should you use instead?
Show answer
math.log2 converts n to a float. For values just below a power of 2, such as 2**60 - 1, the conversion rounds up to the power of 2, so the computed log is one too high. Use n.bit_length() for an exact integer count.