Sub topic 8
Loops That Halve or Double
This chapter assumes you can read Python while loops, count the iterations of a simple loop from its bounds, and work with logarithms such as log₂ 8 = 3.
Most loops change their control variable by adding or subtracting a fixed amount. That gives a count proportional to n. Some loops instead multiply or divide the variable by a constant. Those loops finish much faster: their iteration count grows with the logarithm of n.
The Halving Loop
Here is a loop that divides n by 2 until it reaches 0:
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)) # 10Each pass cuts the remaining value in half. After k passes the value is about n / 2ᵏ. The loop stops when that value drops below 1, which happens once 2ᵏ > n, or k > log₂ n. For n ≥ 1 the exact count is ⌊log₂ n⌋ + 1. In Python that is n.bit_length(), because each halving removes one binary digit.
The count grows very slowly:
| n | Iterations (⌊log₂ n⌋ + 1) |
|---|---|
| 1 | 1 |
| 8 | 4 |
| 1,000 | 10 |
| 1,000,000 | 20 |
Multiplying n by 1,000 adds only about 10 iterations.
The Doubling Loop
The mirror image starts small and multiplies until it passes a limit:
import math
def count_doubling(n):
steps = 0
i = 1
while i < n:
i *= 2
steps += 1
return steps
for n in (1, 2, 8, 9, 1000):
assert count_doubling(n) == (n - 1).bit_length()
if n > 1:
assert count_doubling(n) == math.ceil(math.log2(n))
print(count_doubling(9)) # 4 (i goes 1, 2, 4, 8, 16)After k passes, i = 2ᵏ. The loop stops at the first k with 2ᵏ ≥ n, so the count is ⌈log₂ n⌉ for n ≥ 1. The exact formulas for halving and doubling differ by one depending on whether the condition uses <, <=, or > 0, but both counts are about log₂ n.
Other Bases
Dividing by 3, or by 10, follows the same reasoning with a different base: about log₃ n or log₁₀ n iterations. Logarithms in different bases differ only by a constant factor (log₃ n = log₂ n / log₂ 3), so all of these loops have the same order of growth. A later chapter covers dropping constants properly.
Common Errors
- Mistaking a big step for a logarithm.
n -= 2ori += 100still changes the variable by a fixed amount, so the count is linear (n/2 or n/100). The count is logarithmic only when the variable is multiplied or divided. - Writing
i += iand not noticing it doubles. That line is the same asi *= 2, so the loop is logarithmic. - Starting a doubling loop at 0.
i = 0; i *= 2never changes, so the loop never ends. Doubling loops have to start at a positive value. - Off-by-one in the exact count. Trace n = 1 and a small power of two by hand to check whether your formula needs the +1 or the ceiling.
Exercise
How many times does the body of i = 1; while i <= n: i *= 3 run when n = 100? Give a general formula for n ≥ 1.
Show answer
i takes the values 1, 3, 9, 27, 81, and the next value, 243, exceeds 100, so the body runs 5 times. In general the count is ⌊log₃ n⌋ + 1, since the loop runs for every power 3ᵏ ≤ n with k = 0, 1, ..., ⌊log₃ n⌋.
Exercise
A loop runs while n > 0: n -= 2. Is it logarithmic? How many iterations does it run for a positive integer n?
Show answer
It is not logarithmic, because subtracting a constant is a fixed-size step. It runs ⌈n/2⌉ times, which grows linearly with n.