These are the human proofs of Dirichlet hyperbola method, at full length.
The hyperbola method returns D(n) after exactly floor(sqrt n) divisions full
This proof shows: correctness, termination, time.worst, time.best.
We use the pseudocode HYPERBOLA-D of the page. For an integer n, D(n)=∑k=1nd(k), where d(k) is the number of positive divisors of k, and D(n)=0 for n≤0.
Lemma 1 (pairs). For n≥1 let P={(a,b)∈Z≥12:ab≤n}. Then ∣P∣=D(n).
Proof. The map (a,b)↦ab sends P to {1,…,n}. The pairs with ab=k are the (a,k/a) with a a positive divisor of k, so there are d(k) of them. Summing over k≤n gives ∣P∣=D(n). □
Lemma 2 (columns). For a≥1, the number of b≥1 with ab≤n is ⌊n/a⌋.
Proof.ab≤n if and only if b≤n/a, and the positive integers b≤n/a are 1,…,⌊n/a⌋. □
Proof. If n≤0, line L1 returns 0=D(n). Let n≥1. Line L2 sets s with s2≤n<(s+1)2, so s≥1.
Loop invariant. At the start of the iteration with value a of line L4, t=∑a′=1a−1⌊n/a′⌋. It holds for a=1 with t=0 (line L3), and line L5 adds the term for a, so it holds for a+1. When the loop ends, t=∑a=1s⌊n/a⌋.
Let A={(a,b)∈P:a≤s} and B={(a,b)∈P:b≤s}.
By Lemma 2, ∣A∣=∑a≤s⌊n/a⌋=t.
The swap (a,b)↦(b,a) is a bijection of P onto itself, since ab=ba, and it maps A onto B. So ∣B∣=t.
A∪B=P: if (a,b)∈P with a≥s+1 and b≥s+1, then ab≥(s+1)2>n, which is false.
A∩B={1,…,s}2: each pair with a,b≤s has ab≤s2≤n, so it is in P, and it is in A and in B; the converse is the definition. So ∣A∩B∣=s2.
By inclusion and exclusion and Lemma 1, D(n)=∣P∣=∣A∣+∣B∣−∣A∩B∣=2t−s2, which line L6 returns. □
Theorem 2 (general form). Let f,g be functions on the positive integers, F(x)=∑a≤xf(a) and G(x)=∑b≤xg(b). For n≥1 and s=⌊n⌋,
Proof. Give the point (a,b) the weight f(a)g(b). By Lemma 2, the weight of the column a is f(a)G(⌊n/a⌋), so the weight of A is the first sum. In the same way the weight of the row b is g(b)F(⌊n/b⌋), and the weight of B is the second sum. The weight of A∩B={1,…,s}2 is ∑a≤s∑b≤sf(a)g(b)=F(s)G(s). Facts 3 and 4 above hold as before, so inclusion and exclusion for weights gives the formula. With f=g=1 the left side is D(n) and the formula reduces to Theorem 1. □
Theorem 3 (cost). For n≥1 the loop of lines L4 and L5 runs exactly ⌊n⌋ times, with one division and one addition per iteration, and the algorithm uses O(1) words besides the input.
Proof. The loop runs over a=1,…,s with no early exit, so it terminates after exactly s iterations, and n−1<s≤n. The variables are s, t and a. So the time is Θ(n) word operations in every case, best and worst alike, plus the cost of the integer square root of line L2, which Newton's method computes in O(logn) steps. For n≤0 the time is O(1). ■