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

010k20k30k20004000ncount
Measured
Table
ncount
820
1650
32119
64280
128645
2561,466
5123,280
10247,262
204815,937
409634,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
  1. For each i the inner loop visits ⌊n/i⌋ multiples.
  2. Σ n/i = n · (1 + 1/2 + 1/3 + … + 1/n) = n · Hₙ.
  3. 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.