Algorithm Search⌘K

Proofs: Divisor-count sieve

These are the human proofs of Divisor-count sieve, at full length.

The divisor-count sieve computes d(m) for every m up to n full

This proof shows: correctness.

Fix mm with 1≤m≤n1 \le m \le n. Line L1 sets d[m]=0d[m] = 0, and line L4 is the only line that changes d[m]d[m]; each run adds 1. So at the end, d[m]d[m] equals the number of pairs (e,j)(e, j) for which line L4 runs with m=jem = j e, that is, with ee the value of the outer loop and j≥1j \ge 1 the step of the inner loop.

Claim. Line L4 runs at the index mm exactly once for each positive divisor ee of mm, and never for any other ee.

Proof. For a fixed ee with 1≤e≤n1 \le e \le n, the loop of line L3 takes the values m′=e,2e,3e,…m' = e, 2e, 3e, \ldots while m′≤nm' \le n. These values are distinct, and they are exactly the multiples of ee in [1,n][1, n]. So the index mm appears in the round of ee once if e∣me \mid m, and not at all otherwise. Every positive divisor ee of mm satisfies 1≤e≤m≤n1 \le e \le m \le n, so the loop of line L2 reaches it. □\square

By the claim, d[m]d[m] ends equal to the number of positive divisors of mm, which is d(m)d(m). No run of line L4 writes index 0, since m′≥e≥1m' \ge e \ge 1, so d[0]=0d[0] = 0. The loops terminate: the outer loop runs nn times, and the round of ee runs ⌊n/e⌋\lfloor n/e \rfloor times. ■\blacksquare

The same argument, with line L4 adding eke^k instead of 1, shows that the variant computes σk(m)=∑e∣mek\sigma_k(m) = \sum_{e \mid m} e^k.

The count of runs. By the claim, the total number of runs of line L4 is ∑m≤nd(m)\sum_{m \le n} d(m), and counting by ee instead gives ∑e≤n⌊n/e⌋\sum_{e \le n} \lfloor n/e \rfloor. These two sums are equal, which is the identity used in the complexity section.

Back to Divisor-count sieve