Search⌘ K

Fast Multiplication

Explore fast multiplication methods with recursion by implementing the Karatsuba algorithm. Understand how splitting numbers and reducing recursive calls optimizes multiplication beyond the traditional quadratic approach. This lesson guides you through the divide-and-conquer strategy and its improvements for efficient number multiplication.

Divide-and-conquer algorithm

Two ancient algorithms for multiplying two nn-digit numbers in O(n2)O(n^2) time are the grade-school lattice algorithm and the Egyptian peasant algorithm. Maybe we can get a more efficient algorithm by splitting the digit arrays in half and exploiting the following identity:

(10ma+b)(10mc+d)=102mac+10m(bc+ad)+bd(10^ma + b)(10^mc + d) = 10^{2m}ac + 10^m(bc + ad) + bd

This recurrence immediately suggests the following divide-and-conquer algorithm to multiply two nn-digit numbers, xx and yy. Each of the four sub-products ac,bc,ad,ac, bc, ad, and bdbd is computed recursively, but the multiplications in the last line are not recursive because we can multiply by a power of ten by shifting the digits to the left and filling in the correct number of zeros, all in O(n)O(n) time.

Algorithm


SplitMultiply(x,y,n):if n=1return xyelsemn/2ax/10m; bx mod 10m〈〈x=10m a+b〉〉cy/10m; dy mod 10m〈〈y=10m c+d〉〉eSplitMultiply(a,c,m)fSplitMultiply(b,d,m)gSplitMultiply(b,c,m)hSplitMultiply(a,d,m)return 102me+10m(g+h)+f\underline{SplitMultiply(x, y,n):} \\ \hspace{0.4cm} if\space n = 1 \\ \hspace{1cm} return\space x · y \\ \hspace{0.42cm} else \\ \hspace{1cm} m ← ⌈n/2⌉ \\ \hspace{1cm} a←⌊x/10^m⌋; \space b←x\space mod\space 10^m \hspace{1cm} {\color{Red}〈〈x=10^m \space a+b〉〉 } \\ \hspace{1cm} c←⌊y/10^m⌋;\space d←y\space mod\space10^m \hspace{1cm} {\color{Red}〈〈y=10^m \space c+d〉〉 } \\ \hspace{1cm} e ← SplitMultiply(a, c, m) \\ \hspace{1cm} f ←SplitMultiply(b,d,m) \\ \hspace{1cm} g ← SplitMultiply(b, c, m) \\ \hspace{1cm} h←SplitMultiply(a,d,m) \\ \hspace{1cm} return\space 10^{2m}e + 10^m(g + h) + f ...