"Overview"
Karatsuba multiplication is a fast multiplication. This algorithm was presented in 1960 by Anatolii Alexeevitch Karatsuba and published in 1962.
This algorithm is mainly used to multiply two large numbers. The complexity of the common multiplication is n2, while the complexity of the Karatsuba algorithm is only 3nlog3≈3n1.585 (Log3 is the base of 2)
"Step "
The Karatsuba algorithm is mainly used to multiply two large numbers, the principle is to divide the large number into two segments into smaller digits, and then do 3 multiplication, with a small number of addition operations and shift operations.
Existing two large numbers, X, Y.
First, x, Y is disassembled into two parts, which can be x1,x0,y1,y0. Their relationship is as follows:
x = x1 * tenm + x0;
y = y1 * Tenm + y0. where M is a positive integer, M < n, and X0,y0 is less than tenm.
So
XY = (x1 * Tenm + x0) (y1 * + y0)
=Z2 * 2m + z1 *m + z0, where:
z2 = x1 * y1;
Z1 = x1 * y0 + x0 * y1;
z0 = x0 * y0.
This step requires a total of 4 multiplication, but only 3 multiplication after the Karatsuba improvement. Because:
Z1 = x1 * y0+ x0 * y1
Z1 = (x1 + x0) * (y1 + y0)-X1 * y1-x0 * y0,
Therefore x0 * y0 can be obtained by adding and subtracting.
So:
X*y = z2 *2m + z1 * Tenm + z0
z2 = x1 * Y1
Z1 = (x1 + x0) * (y1 + y0)-X1 * y1-x0 * y0 = (x1 + x0) * (y1 + y0)-X1 * y1-z0
z0 = x0 * y0
Recursively computer (X1*Y1)
Recursively computer (x1 + x0) * (y1 + y0)
Recursively computer (x0 * y0)
"Example Explanation"
Set x = 12345,y=6789, make m=3. Then there are:
12345 = 12 * 1000 + 345;
6789 = 6 * 1000 + 789.
The following calculation:
Z2 = 12 * 6 = 72;
z0 = 345 * 789 = 272205;
Z1 = (+ 345) * (6 + 789)-z2-z0 = 11538.
We then follow the shift formula (XY = z2 * + z1 * + z0) to get:
XY = 72 * 10002 + 11538 * 1000 + 272205 = 83810205.
"Pseudo Code"
procedureKaratsuba(Num1,Num2) if (Num1< Ten)Or(Num2< Ten) returnNum1*Num2/ * Calculates the size of the numbers * *M= Max(Size_base10(Num1),Size_base10(Num2))M2=M/2 / * Split the digit sequences about the middle * /X0,X1=Split_at(Num1,M2)Y0,Y1=Split_at(Num2,M2) / * 3 calls made to numbers approximately half the size * /Z0=Karatsuba(X0, y0)Z1=Karatsuba((X0+Y1),(X1+Y0))Z2=Karatsuba(X1,Y1) return (Z2*Ten^(2*M2))+((Z1-Z2-Z0)*Ten^(M2))+(Z0)
"Code"
Algorithm Karatsuba Fast Multiplication algorithm