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
v=(vn−1…v1v0)b,1≤α≤b−1,y=(yn−1…y1y0)b,0≤k0≤b−1.
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
αvi+yi+ki=(αvi+yi+ki)modb+⌊(αvi+yi+ki)/b⌋b=zi+ki+1b.
Then we have
αv+y=i=0∑n−1(αvi+yi)bi=i=0∑n−1(αvi+yi+ki)bi−i=0∑n−1kibi=i=0∑n−1(zi+ki+1b)bi−i=0∑n−1kibi=i=0∑n−1zibi+i=0∑n−1ki+ibi+1−i=0∑n−1kibi=i=0∑n−1zibi+znbn−k0=z−k0,
which is what we wanted.
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.
Putting these pieces together we get:
(wn…w1w0)b(wn+1…w2w1)b(wn+m−1…wmwm−1)b←u0v,←(wn…w2w1)+u1v,⋮←(wn+m−2…wmwm−1)b+um−1v.
The algorithm can actually be generalized slightly if we compute
w←(wn−1…w1w0)b+uv
instead. All we need to do is replace the first step in the algorithm by
(wn…w1w0)b←(wn−1…w1w0)b+u0v.