This post will cover a basic addition algorithm for multiple-precision non-negative integers. The algorithm is based upon that presented in Section 4.3.1, The Classical Algorithms, of The Art of Computer Programming, Volume 2, by Donald E. Knuth. The notation and bounds used in this post were presented in a previous post.
We consider adding two n-digit numbers with n≥1, u=(un−1…u1u0)b and v=(vn−1…v1v0)b. Since bn−1≤u,v≤bn−1 we have 2bn−1≤u+v≤2bn−2 which, when using the fact that b≥2, leads to bn−1≤u+v≤bn+1−1 (note how a tighter bound of the form bp≤u+v≤bq−1 is not possible).
This means that u+v can be represented using n or n+1 digits, so we set w=(wn…w1w0)b.
Assuming k0 is set to some initial value (more on this below) we now have the following algorithm:
wiki+1←(ui+vi+ki)modb←⌊(ui+vi+ki)/b⌋
for i=0,1,…,n−1, and finally wn←kn.
The algorithm sets the digits of w such that w=u+v+k0. This can be seen by first observing that p=pmodb+⌊p/b⌋b for any integer p. Using this relation on the variables set during the algorithm, we have
ui+vi+ki=wi+ki+1b
for i=0,1,…,n−1. We now 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+knbn−k0,
showing that w=u+v+k0.
It is clear that each resulting digits of w satisfies 0≤wi≤b−1 for i=0,…,n−1, as it should. The value of wn, though, depends on kn.
Assume that 0≤ki≤1 for some i=0,…,n−1. Since ui+vi+ki≤b−1+b−1+1=2b−1 we see that ki+1=⌊(ui+vi+ki)/b⌋≤1. So if we have 0≤k0≤1 as initial value for the algorithm we have, by induction, that 0≤ki≤1 for all i=0,…,n.
This shows how (not surprisingly) k0 can be seen as an “initial carry” and how each ki+1 is 0 or 1, depending on whether a carry was produced from the ith digit addition.