We now turn to multiple-precision subtraction for non-negative integers. The algorithm is very similar to that of multiple-precision addition, but some minor differences make it worth while considering subtraction separately.
We consider two n-digit numbers, u=(un−1…u1u0)b and v=(vn−1…v1v0)b, with n≥1 (see a previous post on the number notation). We wish to compute an n-digit result w=(wn−1…w1w0)b such that
w=(u−v−k0)modbn
where k0 is some initial borrow, 0≤k0≤1. Furthermore, a final borrow kn will indicate whether u<v+k0.
Let us first introduce a notation which Donald E. Knuth refers to as Iverson's convention: [P] has value 1 if P is true and 0 otherwise.
We now have the algorithm:
wiki+1←(ui−vi−ki)modb,←[ui<vi+ki],
for i=0,1,…,n−1. This is really just a formalization of the familiar pencil-and-paper method, but let us show that it does the right thing.
Note first that 0≤ki≤1 for i=0,1,…,n−1. This is a consequence of the assumption 0≤k0≤1 for the initial borrow and the range of the [⋅] operator. We next establish the relation
−⌊bui−vi−ki⌋=[ui<vi+ki],
which holds since we have −b=0−(b−1)−1≤ui−vi−ki≤(b−1)−0−0=b−1. We now observe that
ui−vi−ki=(ui−vi−ki)modb+⌊bui−vi−ki⌋b=(ui−vi−ki)modb−[ui<vi+ki]b=wi−ki+1b.
We finally have
u−v=i=0∑n−1(ui−vi)bi=i=0∑n−1(ui−vi−ki)bi+i=0∑n−1kibi=i=0∑n−1(wi−ki+1b)bi+i=0∑n−1kibi=i=0∑n−1wibi−i=0∑n−1ki+1bi+1+i=0∑n−1kibi=w−knbn+k0,
so u−v−k0=w−knbn. Since 0≤w≤bn−1 we have now established
w=(u−v−k0)modbn,
and kn indicates whether u<v+k0.