Non-restoring division computes the quotient and the remainder full
This proof shows: correctness, termination.
Let U≥0 have the binary digits um−1…u0 and let V≥1. Put Pi=⌊U/2i⌋, so Pm=0, P0=U and Pi=2Pi+1+ui. Let Rm=0 be the value set by line L1, and Ri the value of R after the step for i. Define the restored value
Ti={RiRi+Vif Ri≥0,if Ri<0. Let Qi=∑j≥iqj2j−i be the number formed by the quotient digits after the step for i, with Qm=0.
Lemma. For i=m,…,0: −V≤Ri<V, 0≤Ti<V, and Pi=QiV+Ti. Moreover, for i<m, Ri=2Ti+1+ui−V.
Proof. By downward induction. For i=m: Rm=Tm=0 and Pm=0=0⋅V+0.
Assume the claims for i+1. First, Ri=2Ti+1+ui−V:
- if Ri+1≥0, line L3 gives Ri=2Ri+1+ui−V=2Ti+1+ui−V;
- if Ri+1<0, then Ri+1=Ti+1−V, and line L4 gives Ri=2(Ti+1−V)+ui+V=2Ti+1+ui−V.
Let S=2Ti+1+ui. Since 0≤Ti+1≤V−1 and ui∈{0,1}, 0≤S≤2V−1, so Ri=S−V∈[−V,V−1]. Also Pi=2Pi+1+ui=2Qi+1V+S.
- If Ri≥0: qi=1, Qi=2Qi+1+1 and Ti=Ri=S−V∈[0,V), so QiV+Ti=2Qi+1V+S=Pi.
- If Ri<0: qi=0, Qi=2Qi+1 and Ti=Ri+V=S∈[0,V), so QiV+Ti=2Qi+1V+S=Pi.
So the claims hold for i. □
Theorem. NON-RESTORING-DIV terminates after m steps and one optional correction, and returns Q=⌊U/V⌋ and R=UmodV.
Proof. The loop runs over m values of i with a bounded amount of work each, and line L6 runs at most once, so the algorithm terminates. Line L6 replaces R0 by T0. By the lemma for i=0, U=Q0V+T0 with 0≤T0<V, so by the uniqueness of division with remainder Q0=⌊U/V⌋ and T0=UmodV. The returned digits qm−1,…,q0 are the binary digits of Q0. □
The form with digits ±1. Let di=1 if Ri+1≥0 and di=−1 otherwise, the operation chosen in step i. Then Ri=2Ri+1+ui−diV in both lines L3 and L4. Multiplying by 2i and summing over i=m−1,…,0, the terms 2i+1Ri+1 and 2iRi telescope, and with Rm=0,
R0=i<m∑ui2i−Vi<m∑di2i=U−DV,D=i<m∑di2i. Since R0∈[−V,V), Q=D and R=R0 if R0≥0, and Q=D−1 and R=R0+V if R0<0. This is the textbook correction.
Register widths. The implementation holds R in two's complement in n+1 limbs of w≥2 binary digits, with V<2nw. The intermediate value 2R+ui lies in [−2V,2V), and 2V≤2nw+1≤2(n+1)w−1 because w≥2, so every intermediate value lies in the range [−2(n+1)w−1,2(n+1)w−1) of the register. Arithmetic modulo 2(n+1)w therefore represents each value exactly, and the top binary digit is its sign. ■