After addressing multiple-precision addition
and subtraction,
we now turn to multiplication of two multiple-precision numbers.
Once again, we use the number representation and notation introduced earlier.
Several algorithms exist for doing multiple-precision multiplication. This post will present the basic, pencil-and-paper-like method. Basically, it consists of two parts: Multiplying a number by a single digit and adding together the sub-results, aligned appropriately.
Multiple digits times a single digit
Let us first consider multiplying an n-digit multiple-precision integer by a single digit. More precisely, we wish to compute z←αv+y+k0 where
Using this information it is straightforward to show that bn−1≤z≤bn+1−1, which implies that the result will fit into n or n+1 digits, so we set z=(zn…z1z0)b, where zn may be zero.
We now have the algorithm:
ziki+1←(αvi+yi+ki)modb,←⌊bαvi+yi+ki⌋,
for i=0,1,…,n−1 and finally setting zn=kn.
To realize that the algorithm computes what it is supposed to, observe first that
From the expression for zi we see that they naturally fit into a digit, that is, 0≤zi≤b−1 for i=0,1,…,n−1. But what about the ki's and thus also zn? Assume that 0≤ki≤b−1. We then have
αvi+yi+ki≤(b−1)+(b−1)(b−1)+(b−1)=b2−1,
which implies that ki+1=⌊(αvi+yi+ki)/b⌋≤b−1. Since we have also assumed 0≤k0≤b−1 we have, by induction, that 0≤zi≤b−1 for i=0,1,…,n.
Multiple digits times multiple digits
We now turn to multiplying two multiple-precision numbers. More specifically, we wish to multiply
u=(um−1…u1u0)b,andv=(vn−1…v1v0)b,
which implies bm+n−2≤uv<bm+n. So we set w=(wm+n−1…w1w0)b and aim to compute
w←uv=i=0∑m−1uivbi.
We observe two things:
Multiplication by bi corresponds to shifting left the number of digits given by i.
The product uiv is of type single-digit times multiple-digit and can be computed using the algorithm from the previous section.