Karatsuba Multiplication

From Algorithmist
Jump to navigation Jump to search

Karatsuba Multiplication is a faster algorithm for BigNum or BigInt multiplication that is still fairly simple to implement. Its runtime complexity is , although it involves more additions and subtractions than the naive algorithm.

It is based on the clever observation that to find (which is ), we need only three multiplications, while the naive method of multiplying them out would take four multiplications. The three multiplications are:

The coefficient of , namely can therefore be found by subtracting the results of the first two multiplications from that of the third, thereby saving us one multiplication.

What this means for BigNums is that given two integers and of about digits each, we can write them as and (by taking to be the integer formed by the first half of the digits of , etc). Now, we can use the above observation to compute . (Note that multiplying by a power of 10 (or in general, the base we are working with) simply consists of shifting the digits a certain number of places, as we are doing in the naive multiplication algorithm, too.) Thus, the time taken by this algorithm to multiply two integers of length is , which gives a runtime of .

Extensions of Karatsuba[edit]

In Karatsuba multiplication, we break the multiplicands into two parts. What happens if, say, we break them into three parts? This leads to the Toom-Cook 3-way multiplication algorithm, which has an asymptotic runtime of . This is asymptotically faster than Karatsuba, but the algorithm requires more work to be done in post-processing after the recursive multiplications are done.

Obviously the idea can be extended to break the multiplicands into even more pieces, but at some point the amount of work needed to recover the actual digits outweighs the work saved in the clever formulation of the problem.