Exercise 29 of 30 · advanced · loops · harmonic series · linearithmic · sieve
Inner loop stepping by the outer index
The code
for i in range(1, n + 1):
for j in range(i, n + 1, i): # multiples of i
mark(j)The inner loop runs n/i times. What is the sum?
Count: mark calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 20 |
| 16 | 50 |
| 32 | 119 |
| 64 | 280 |
| 128 | 645 |
| 256 | 1,466 |
| 512 | 3,280 |
| 1024 | 7,262 |
| 2048 | 15,937 |
| 4096 | 34,720 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n log n)
- Extra space
- O(1)
- Exact count
- Σ ⌊n/i⌋ ≈ n · Hₙ ≈ n ln n
- For each i the inner loop visits ⌊n/i⌋ multiples.
- Σ n/i = n · (1 + 1/2 + 1/3 + … + 1/n) = n · Hₙ.
- The harmonic number Hₙ ≈ ln n, so the total is Θ(n log n). The sieve of Eratosthenes, which loops only over primes, is Θ(n log log n).
Common mistake: Answering Θ(n²) because both loops go up to n.
Check: measured count ÷ (n log n) settles near 0.706 for large n.