For an integer P≥0, the integer q≥0 satisfies q=⌊P⌋ if and only if q2≤P<(q+1)2, that is, if and only if 0≤P−q2≤2q.
Invariant. After j passes of the loop of line L2, q=⌊Pj⌋ and r=Pj−q2, so 0≤r≤2q.
Initialization. Line L1 sets q=r=0, and ⌊P0⌋=0, P0−0=0.
Maintenance. Assume the invariant after j passes, with values q and r. Line L3 sets ρ=rβ2+gj=Pj+1−q2β2.
Step 1: the new root lies in a range of β values. Let Q′=⌊Pj+1⌋. First, (qβ)2=q2β2≤Pjβ2≤Pj+1, so Q′≥qβ. Second, Pj≤(q+1)2−1 by the invariant, so
Pj+1≤((q+1)2−1)β2+β2−1=(q+1)2β2−1<((q+1)β)2,
and Q′<(q+1)β. Hence Q′=qβ+x∗ for a unique x∗∈{0,…,β−1}.
Step 2: line L4 finds x∗. For each x∈{0,…,β−1},
(qβ+x)2=q2β2+(2qβ+x)x,
so (qβ+x)2≤Pj+1 holds if and only if (2qβ+x)x≤ρ. The left side (2qβ+x)x increases with x, so the set of digits x that satisfy the test is an initial segment {0,…,xmax}, which contains 0. Its largest element is the largest x with (qβ+x)2≤Pj+1. By Step 1 this is x∗: (qβ+x∗)2=Q′2≤Pj+1, and for x∗<x≤β−1, qβ+x>Q′ gives (qβ+x)2>Pj+1. So line L4 sets x=x∗. (The binary search of the implementation keeps lo≤x∗≤hi, since the test holds at lo and the set is an initial segment, so it ends with lo=hi=x∗.)
Step 3: the new values. Line L6 sets q′=qβ+x∗=Q′, and line L5 sets
r′=ρ−(2qβ+x∗)x∗=Pj+1−q2β2−(2qβ+x∗)x∗=Pj+1−Q′2.
So the invariant holds after j+1 passes, and 0≤r′≤2q′ follows from Q′=⌊Pj+1⌋.
Termination. The loop of line L2 runs n times, and line L4 examines at most β candidates.
Theorem. DIGIT-SQRT returns q=⌊A⌋ and r=A−q2, with 0≤r≤2q. The digits appended in line L6 are the n base β digits of q, most significant first.
Proof. After n passes the invariant gives q=⌊Pn⌋=⌊A⌋ and r=A−q2. Each pass replaces q by qβ+x with 0≤x<β, so the values x in order are the digits of q, and q<βn because A<β2n. ■