The Newton reciprocal is exact after a bounded correction, and the quotient is off by at most one full
This proof shows: correctness, termination.
For an integer D≥1 let B=B(D) be its binary length, so 2B−1≤D<2B, and let R∗=4B/D, a real number. Then 2B<R∗≤2B+1.
Theorem. RECIPROCAL(D) terminates and returns ⌊4B/D⌋; the loop of line L7 runs at most 16 times in each call. For 0≤U<D2B and R=⌊4B/D⌋, DIVIDE(U,D,R) terminates and returns (⌊U/D⌋,UmodD), and the loop of line L10 runs at most once.
1. Termination of the recursion. If B>B0≥1, then h=⌈B/2⌉ satisfies 1≤h<B, and Dh=⌊D/2B−h⌋ has binary length exactly h, since 2B−1/2B−h=2h−1 and D/2B−h<2h. So each call recurses once on a divisor of strictly smaller length, and the recursion ends at line L1 after at most ⌈log2B⌉ levels. Line L1 is correct by definition. We now prove a call at length B>B0 correct, assuming that the recursive call returns Xh=⌊4h/Dh⌋ (induction on B).
2. The start. Let X0=Xh2B−h, the value of line L4, and t=2B−h. Then −t<X0−R∗<4t.
Proof. Put d′=D/t, a real number with Dh≤d′<Dh+1. Then R∗/t=4B/(Dt)=2B+h/D=4h/d′, since d′=D/2B−h. Now 4h/Dh−1<Xh≤4h/Dh, and
0≤Dh4h−d′4h=Dhd′4h(d′−Dh)<Dh24h≤4h−14h=4, using Dh≥2h−1. Hence −1<Xh−4h/d′<4, and multiplying by t gives the claim. □
3. The Newton step squares the residual. For any real X, let E=4B−DX and X∗=X+XE/4B. Then
4B−DX∗=4B−DX−4BDX⋅E=E−4B(4B−E)E=4BE2≥0, so X∗≤R∗ and R∗−X∗=E2/(4BD). □
4. After line L6. Let X1 be the value after line L6. Then R∗−17<X1≤⌊R∗⌋.
Proof. With X=X0, line L5 computes the integer E=4B−DX0=D(R∗−X0). If E≥0, line L6 sets X1=X0+⌊X0E/4B⌋; if E<0, it sets X1=X0−⌈X0∣E∣/4B⌉. In both cases X1=⌊X∗⌋ where X∗=X0+X0E/4B, because X0 is an integer and −⌈y⌉=⌊−y⌋. By part 3, X∗≤R∗, so the integer X1≤⌊R∗⌋. By part 2, ∣E∣<4Dt, so by part 3
R∗−X∗=4BDE2<4BD16D2t2=4B16D4B−h=4h16D<16, since D<2B≤22h=4h. With X1>X∗−1 this gives X1>R∗−17. □
5. Line L7. Line L7 sets E=4B−DX1=D(R∗−X1)≥0 and keeps the invariant E=4B−DX while it increments X and subtracts D from E. It stops when 0≤E<D, that is, when X≤R∗<X+1, that is, when X=⌊R∗⌋. Starting from X1≤⌊R∗⌋, it reaches this value after ⌊R∗⌋−X1 steps, an integer with ⌊R∗⌋−X1≤R∗−X1<17. So it runs at most 16 times and line L8 returns ⌊4B/D⌋. This completes the induction. □
6. The quotient. Let 0≤U<D2B and R=⌊R∗⌋, so R∗−1<R≤R∗. Line L9 sets q=⌊UR/4B⌋. From R≤R∗, q≤UR∗/4B=U/D, so q≤⌊U/D⌋. From R>R∗−1 and U<D2B≤4B (as D<2B),
q>4BUR−1>DU−4BU−1>DU−2≥⌊DU⌋−2, so the integer q≥⌊U/D⌋−1. Then r=U−qD satisfies 0≤r<2D, and line L10 subtracts D at most once, keeping U=qD+r, and stops with 0≤r<D. By the uniqueness of division with remainder, q=⌊U/D⌋ and r=UmodD. □
7. Long dividends. DIVIDE on blocks keeps the invariant that, after the blocks above position j are processed, q and r are the quotient and remainder of the number formed by those blocks; each block step has U=r2B+block<D2B since r<D, so part 6 applies. This is the invariant of long division with digits of B binary digits. ■