Russian peasant multiplication computes the exact product full
This proof shows: correctness, termination.
Let x0≥0 and y0≥0 be integers, the inputs of PEASANT-MUL.
Theorem. PEASANT-MUL(x0,y0) terminates after exactly N rounds of the loop of line L2, where N=0 if y0=0 and N=⌊log2y0⌋+1 otherwise, and it returns x0y0.
Proof. Write xr,yr,pr for the values of x,y,p after r rounds, so x0,y0 are the inputs and p0=0 by line L1. One round gives pr+1=pr+(yrmod2)xr (line L3), xr+1=2xr (line L4) and yr+1=⌊yr/2⌋ (line L5).
Invariant. We show pr+xryr=x0y0 for every r for which round r is reached. For r=0 this is 0+x0y0=x0y0. Assume it for r, and that yr>0, so round r+1 runs. Division with remainder by 2 gives yr=2⌊yr/2⌋+(yrmod2)=2yr+1+(yrmod2). Hence
pr+1+xr+1yr+1=pr+(yrmod2)xr+2xryr+1=pr+xr(2yr+1+(yrmod2))=pr+xryr=x0y0. Termination. By induction, yr=⌊y0/2r⌋, since ⌊⌊u/2r⌋/2⌋=⌊u/2r+1⌋ for integers u≥0. If y0=0 the loop does not run, and N=0. If y0≥1, then 2N−1≤y0<2N, so yr≥1 for r≤N−1 and yN=0. The loop therefore runs exactly N rounds and stops.
Result. When the loop stops, yN=0, and the invariant gives pN=x0y0−xN⋅0=x0y0, which line L6 returns. All values stay nonnegative integers, since p only grows by nonnegative terms, x is doubled and y is halved with the floor.
Limb arrays. In the implementation on limb arrays in radix β=2w, the parity of y is the lowest bit of its lowest limb, since β is even; the doubling shifts each limb left by one bit and carries its top bit into the next limb, which computes 2x exactly because 2∑ixiβi=∑i(2ximodβ)βi+∑i⌊2xi/β⌋βi+1 with ⌊2xi/β⌋∈{0,1}; the halving is the reverse, ⌊y/2⌋=∑i(⌊yi/2⌋+(yi+1mod2)β/2)βi; and line L3 uses an exact multiprecision addition. So each line computes the value the argument above uses. ■