Sub topic 6
Series You Need for Loop Counting
When a loop's work changes from one iteration to the next, you can't just multiply two numbers to get the total. You have to add up a sequence of costs, and that sum is a series. This chapter collects the handful of series that cover almost every loop you will meet. It also shows how to derive and check each one. The next chapter uses these formulas on triangular and dependent nested loops. Here the focus is on the formulas themselves and on the mistakes people make when using them.
This chapter assumes you can read Python for and while loops, that you know exponents and logarithms, and that you have already counted single loops with a start, stop, and step, as in the earlier chapters.
Why Loops Turn Into Sums
The total cost of a loop is the sum of the cost of each iteration. If every iteration costs the same, the sum collapses to "iterations times cost." If the cost depends on the loop variable, you get a sum such as:
- 1 + 2 + 3 + ... + n, when iteration i does i units of work
- n + n/2 + n/4 + ... + 1, when each round of work handles half as much data
- 1 + 2 + 4 + ... + 2^k, when each round handles twice as much
Each pattern has a closed form, a formula that gives the total without adding term by term. The closed form is what turns a loop into an expression like n(n−1)/2, which you can then reduce to an order of growth.
Arithmetic Series
An arithmetic series is a sum where each term differs from the previous one by the same amount, the common difference.
The basic formula
The sum of the first n positive integers is:
1 + 2 + ... + n = n(n + 1) / 2
The classic derivation writes the sum forwards and backwards and adds the two copies:
| Forward | 1 | 2 | ... | n−1 | n |
|---|---|---|---|---|---|
| Backward | n | n−1 | ... | 2 | 1 |
| Column sum | n+1 | n+1 | ... | n+1 | n+1 |
There are n columns, each summing to n + 1, so twice the sum is n(n + 1). Halve it to get the formula.
The zero-based variant
Python loops usually start at 0, so the sum you actually get is often 0 + 1 + ... + (n − 1):
0 + 1 + ... + (n − 1) = n(n − 1) / 2
This is the same formula with n replaced by n − 1. Mixing up the two is the most common off-by-one error in loop counting. For n = 10, the first gives 55 and the second gives 45. Both are Θ(n²), but if you are checking an exact count against an instrumented counter, only the right one will match.
The general form
Any arithmetic series, whatever its start and common difference, follows one rule:
sum = (first term + last term) × (number of terms) / 2
This is the forwards-and-backwards argument again, since every column sums to first + last. It is the most useful version, because you rarely need to memorize anything beyond it. You do need the number of terms, and that comes from the loop-bounds rule in the earlier chapter: for range(a, b, s) with s > 0 and b > a, there are ⌈(b − a)/s⌉ terms.
Take range(3, 20, 4), which yields 3, 7, 11, 15, 19. It has ⌈17/4⌉ = 5 terms, first term 3, and last term 19. The sum is (3 + 19) × 5 / 2 = 55.
import math
def arithmetic_sum(a, b, s):
"""Sum of range(a, b, s) for s > 0, using the closed form."""
if b <= a:
return 0
count = math.ceil((b - a) / s)
last = a + (count - 1) * s
return (a + last) * count // 2
print(arithmetic_sum(3, 20, 4)) # 55
print(sum(range(3, 20, 4))) # 55
for a in range(0, 10):
for b in range(0, 30):
for s in range(1, 6):
assert arithmetic_sum(a, b, s) == sum(range(a, b, s))
print("general arithmetic formula holds")Integer division // is safe here. The true sum of integers is an integer, so (first + last) × count is always even.
Sum of squares
Sometimes a loop's inner work is itself a triangular count, for example in a triple loop where the innermost bound depends on the middle variable. Then you need:
1² + 2² + ... + n² = n(n + 1)(2n + 1) / 6
You don't need to derive this one by hand. Remember that it is Θ(n³), with a leading term of n³/3. The general pattern is that the sum of i^k for i from 1 to n is Θ(n^(k+1)). Summing a polynomial of degree k raises the degree by one.
Geometric Series
A geometric series is a sum where each term is the previous one multiplied by a fixed ratio r. Geometric series appear when a loop doubles or halves something. Examples include a buffer that doubles in size, a loop over 1, 2, 4, 8, ..., or work that shrinks by half each round.
Ratio greater than 1: doubling
The key case is r = 2:
1 + 2 + 4 + ... + 2^k = 2^(k+1) − 1
Each power of two is one more than the sum of all smaller powers. In binary, 2^(k+1) − 1 is k + 1 ones in a row. The practical consequence is that the total is less than twice the last term. When work doubles each round, the final round costs about as much as all the earlier rounds put together.
The general formula for r ≠ 1 is:
1 + r + r² + ... + r^k = (r^(k+1) − 1) / (r − 1)
For any constant r > 1, this is Θ(r^k), a constant multiple of the largest term.
Ratio less than 1: halving
Reverse the order and you get the halving pattern:
n + n/2 + n/4 + ... + 1 < 2n
For r < 1 the infinite series converges:
a + ar + ar² + ... = a / (1 − r)
With a = n and r = 1/2, the bound is 2n. The total is Θ(n), set by the first term. This explains an often-surprising result: a loop that processes n items, then n/2, then n/4, and so on, does linear total work, not n log n. There are log n rounds, but they get cheap quickly.
With Python's floor division, the exact result is neat. The sum of n // 2^i over all i is 2n minus the number of 1 bits in n:
def halving_work(n):
total = 0
while n > 0:
total += n
n //= 2
return total
for n in range(1, 5000):
assert halving_work(n) == 2 * n - bin(n).count("1")
assert halving_work(n) < 2 * n
for k in range(0, 30):
assert sum(2**i for i in range(k + 1)) == 2**(k + 1) - 1
print(halving_work(1000)) # 1994For n = 1000, binary 1111101000 has six 1 bits, so the total is 2000 − 6 = 1994.
The Harmonic Series
The harmonic series is the sum of reciprocals:
H(n) = 1 + 1/2 + 1/3 + ... + 1/n ≈ ln n + 0.5772
It grows without bound, but only logarithmically. In loop counting it appears when iteration i does about n/i work. A sieve-style loop that, for each i, visits the multiples of i up to n is the standard example:
import math
def multiples_work(n):
steps = 0
for i in range(1, n + 1):
for j in range(i, n + 1, i): # about n / i iterations
steps += 1
return steps
for n in (100, 1000, 10000):
w = multiples_work(n)
print(n, w, round(w / (n * math.log(n)), 3))The inner loop runs ⌊n/i⌋ times, so the total is about n × H(n), which is Θ(n log n). The printed ratio comes out a little above 1 and creeps toward 1 as n grows. The constant 0.5772 matters less and less compared with ln n. The harmonic series is the third common route to n log n, besides "n iterations of a log n loop" and divide-and-conquer.
Choosing the Right Series
| Per-iteration work | Series | Closed form | Order |
|---|---|---|---|
| i, for i = 1..n | arithmetic | n(n+1)/2 | Θ(n²) |
| i, for i = 0..n−1 | arithmetic | n(n−1)/2 | Θ(n²) |
| i², for i = 1..n | sum of squares | n(n+1)(2n+1)/6 | Θ(n³) |
| 2^i, for i = 0..k | geometric, r = 2 | 2^(k+1) − 1 | Θ(2^k) |
| n/2^i, until 1 | geometric, r = 1/2 | less than 2n | Θ(n) |
| n/i, for i = 1..n | harmonic | about n ln n | Θ(n log n) |
Common Errors
- Off-by-one in the endpoints. Write down the first and last values the loop variable actually takes before choosing a formula.
range(n)ends at n − 1.range(i + 1, n)is empty when i = n − 1. - Counting rounds instead of summing work. A halving loop has about log₂ n rounds. If each round does work proportional to the current size, though, the total is the geometric sum, Θ(n), not Θ(n log n).
- Assuming every nested loop is n². The inner bound n/i gives n log n, not n². Check how the inner count depends on the outer variable before multiplying.
- Using float division in exact checks. In Python,
n * (n + 1) / 2returns a float, and for very large n it can lose precision. Use//when comparing with integer counters.
Exercise
A loop runs for i in range(2, 50, 3) and the body costs i steps. Give the exact total number of steps using the general arithmetic formula.
Show answer
The number of terms is ceil((50 − 2) / 3) = 16. The last term is 2 + 15 × 3 = 47. The total is (2 + 47) × 16 / 2 = 392. You can check it with sum(range(2, 50, 3)).
Exercise
A function starts with size = 1 and, while size < n, does size steps of work and then doubles size. For n = 1024, what is the exact total, and what is the order of growth in n?
Show answer
The sizes processed are 1, 2, 4, ..., 512, so the total is 2^10 − 1 = 1023. In general the largest term is less than n, so the sum is less than 2n, and the order of growth is Θ(n).
Exercise
For each i from 1 to n, an inner loop runs n // (i * i) times. Is the total work Θ(n), Θ(n log n), or Θ(n²)?
Show answer
The total is about n × (1 + 1/4 + 1/9 + ...). That series of reciprocal squares converges to π²/6, about 1.645, so the total is Θ(n). Unlike the harmonic series, it does not grow with n.