Double dabble produces the decimal digits of its input full
This proof shows: correctness, termination.
Let x=∑k=0n−1xk2k with xk∈{0,1}, and d≥1 with 2n−1<10d; the choice d = the number of decimal digits of 2n−1 satisfies this. For 0≤k≤n let
Xk=⌊2n−kx⌋=m=0∑k−1xn−1−m2k−1−m, the number formed by the first k bits. Then X0=0, Xk+1=2Xk+xn−1−k and Xn=x.
Invariant. After k passes of the loop of line L2: (I1) 0≤D[i]≤9 for each i, and (I2) ∑i=0d−1D[i]10i=Xk.
Initialization. Line L1 sets all digits to 0, and X0=0.
Maintenance. Assume (I1) and (I2) after k passes, and let D be the digits at that moment and b=xn−1−k the next bit. Lines L3 and L4 set E[i]=D[i]+3 if D[i]≥5 and E[i]=D[i] otherwise; by (I1), 0≤E[i]≤12. Lines L5 to L8 compute, for i=0,…,d−1, with c0=b,
ti=2E[i]+ci,D′[i]=timod16,ci+1=⌊ti/16⌋. We show by cases that ci∈{0,1} for each i and that
D′[i]+10ci+1=2D[i]+ci,0≤D′[i]≤9.(∗) Assume ci∈{0,1}, which holds for i=0.
- If D[i]≤4, then E[i]=D[i] and ti=2D[i]+ci≤9<16, so D′[i]=ti and ci+1=0, and (∗) holds.
- If D[i]≥5, then E[i]=D[i]+3 and ti=2D[i]+ci+6. From 5≤D[i]≤9 we get 16≤ti≤25<32, so ci+1=1 and D′[i]=ti−16=2D[i]+ci−10, which lies in {0,…,9} because 10≤2D[i]+ci≤19. Then D′[i]+10ci+1=2D[i]+ci, and (∗) holds.
In both cases ci+1∈{0,1}, so the induction on i goes through. Multiply (∗) by 10i and sum over i=0,…,d−1:
i=0∑d−1D′[i]10i+i=0∑d−1ci+110i+1=2i=0∑d−1D[i]10i+i=0∑d−1ci10i. The carry terms with 1≤i≤d−1 cancel, which leaves
i=0∑d−1D′[i]10i+cd10d=2Xk+b=Xk+1. Since Xk+1≤x≤2n−1<10d and the sum on the left is nonnegative, cd=0. So ∑iD′[i]10i=Xk+1, and (I1) holds for D′ by (∗).
Termination. The loop of line L2 runs once for each of the n bits, and the inner loops run d times each, so the algorithm stops after n passes.
Theorem. DOUBLE-DABBLE returns digits D[0],…,D[d−1]∈{0,…,9} with ∑iD[i]10i=x, which are the decimal digits of x, padded with zeros to d places.
Proof. After n passes, (I1) and (I2) give ∑iD[i]10i=Xn=x with digits in {0,…,9}. The decimal representation with d digits is unique, so these are the decimal digits of x. ■