The ripple-carry adder computes the exact sum full
This proof shows: correctness, termination.
Let n≥0, let a0,…,an−1 and b0,…,bn−1 be bits, and let c0 be a bit. Write A=∑j<naj2j and B=∑j<nbj2j.
Theorem. RIPPLE-ADD(a,b,c0) terminates and returns bits s0,…,sn with ∑j=0nsj2j=A+B+c0.
Proof. The loop of line L2 has n rounds, so the procedure terminates; as a circuit, it is a finite acyclic network of 5n gates, since each carry ci+1 depends only on inputs and on ci.
Lemma (full adder). For bits x,y,z, let p=x⊕y, g=x∧y, s=p⊕z and c′=g∨(p∧z). Then x+y+z=s+2c′, and s,c′ are bits.
Proof of the lemma. There are eight cases; group them by k=x+y. If k=0, then p=g=0, s=z and c′=0, and x+y+z=z=s. If k=1, then p=1, g=0, s=1−z and c′=z, and s+2c′=1−z+2z=1+z. If k=2, then p=0, g=1, s=z and c′=1, and s+2c′=z+2. In each case s+2c′=k+z. □
Invariant. Let ci be the value of c before round i, so c0 is set by line L1. We show by induction on i, for 0≤i≤n, that ci is a bit and
j=0∑i−1sj2j+ci2i=j=0∑i−1(aj+bj)2j+c0. For i=0 both sides are c0. Assume it for i<n. Round i computes, by lines L3 to L6, si and ci+1 as in the lemma with x=ai, y=bi, z=ci, so ai+bi+ci=si+2ci+1, and ci+1 is a bit. Adding (ai+bi)2i to both sides of the invariant for i gives
j=0∑i−1sj2j+(ai+bi+ci)2i=j=0∑i−1sj2j+si2i+ci+12i+1=j=0∑i(aj+bj)2j+c0, which is the invariant for i+1.
Result. For i=n the invariant reads ∑j<nsj2j+cn2n=A+B+c0. Line L7 sets sn=cn, so ∑j=0nsj2j=A+B+c0. Since A+B+c0≤2(2n−1)+1<2n+1, the n+1 bits hold the sum, and each sj is a bit by the lemma.
Radix 2w. The same argument works for limbs in [0,2w−1] with t=ai+bi+ci≤2w+1−1, si=tmod2w and ci+1=⌊t/2w⌋∈{0,1}, by division with remainder: t=si+2wci+1, and the invariant holds with 2j replaced by 2wj.
Two's complement overflow. Let n≥1 and let A′, B′ be the signed values, so A′=A−an−12n and likewise for B′. The exact signed sum (with c0=0) is A′+B′=∑j<n−1sj2j+cn−12n−1+(an−1+bn−1)2n−1−(an−1+bn−1)2n, by the invariant for i=n−1. With an−1+bn−1+cn−1=sn−1+2cn this equals S′+(cn−1−cn)2n, where S′=∑j<n−1sj2j−sn−12n−1 is the signed value of the n-bit result, in [−2n−1,2n−1−1]. So the exact sum equals the stored result, and is in range, if and only if cn−1=cn: when cn−1=cn the two differ by ±2n, and the exact sum lies outside the range. ■