Restoring division computes the quotient and the remainder full
This proof shows: correctness, termination.
Let U≥0 have the binary digits um−1…u0, so U=∑i<mui2i, and let V≥1. For 0≤i≤m let Pi=⌊U/2i⌋=∑j≥iuj2j−i. Then Pm=0, P0=U, and
Pi=2Pi+1+ui(0≤i<m). Let Qi=∑j≥iqj2j−i be the number formed by the quotient digits found so far, after the step for i, and let Ri be the value of R after that step. Put Qm=0 and Rm=0, the values set by line L1.
Lemma (invariant). For i=m,m−1,…,0: Pi=QiV+Ri and 0≤Ri<V.
Proof. By downward induction on i. For i=m: 0=0⋅V+0 and 0≤0<V, since V≥1.
Assume the claim for i+1, and consider the step for i. Line L3 forms R′=2Ri+1+ui. From 0≤Ri+1≤V−1 and ui∈{0,1},
0≤R′≤2V−1. Also Pi=2Pi+1+ui=2Qi+1V+2Ri+1+ui=2Qi+1V+R′. Line L4 forms R′−V, which lies in [−V,V−1].
- If R′−V≥0, lines L5 and L7 set qi=1 and Ri=R′−V, so 0≤Ri≤V−1, and Qi=2Qi+1+1. Then QiV+Ri=2Qi+1V+V+R′−V=Pi.
- If R′−V<0, line L6 adds V back, so Ri=R′ with 0≤R′<V, and qi=0, Qi=2Qi+1. Then QiV+Ri=2Qi+1V+R′=Pi.
In both cases the claim holds for i. □
Theorem. RESTORING-DIV terminates after m steps and returns Q=⌊U/V⌋ and R=U−QV, with 0≤R<V.
Proof. The loop of line L2 runs over the m values i=m−1,…,0, and each step does a bounded amount of work, so it terminates. By the lemma for i=0, U=P0=Q0V+R0 with 0≤R0<V. By the uniqueness of division with remainder, Q0=⌊U/V⌋ and R0=UmodV, and these are the returned values, since the digits qm−1,…,q0 are the binary digits of Q0.
The sign test in finite registers. The implementation holds R in n+1 limbs of w binary digits, where V<2nw. By the bounds above, 0≤R′≤2V−1<2nw+1≤2(n+1)w, so line L3 never overflows. The subtraction of line L4 is done modulo 2(n+1)w, and its borrow out is 1 exactly when R′<V, which is the test of line L5. In that case the addition of line L6, also modulo 2(n+1)w, gives (R′−V)+V≡R′, and since 0≤R′<2(n+1)w the stored value is R′. So the register computation agrees with the integer one. ■