The Karatsuba algorithm, developed by Anatoly Karatsuba in 1960, is a multiplication algorithm that uses a divide-and-conquer approach to multiply two large numbers, leading to a reduced number of recursive multiplications required and, hence, faster multiplication results.
The traditional grade school algorithm, also known as long multiplication, has a time complexity of
The karatsuba algorithm can be broken down into 3 steps; divide, conquer, and combine. Let's understand what happens at each of these steps when dividing two numbers X and Y:
Divide: In this step, we break both the numbers into two equal halves of lengths
X = X1, X2
Y = Y1, Y2
Conquer: In this step, we recursively compute the following three products of the
P1 = X1 * Y1
P2 = X₂ * Y₂
P3 = (X₁ + X₂) * (Y₁ + Y₂) - P1 - P2
Combine: In the final step, we perform some additions to compute the final product XY as:
X * Y = P₁ * 10n + P3 * 10(n/2) + P2
Let's look at a simple example to understand the working of the Karatsuba algorithm:
The following is an implementation of the Karatsuba algorithm in Python:
def karatsuba(x, y):# Base caseif x < 10 or y < 10:return x * y# Recursive caseelse:# Dividen = max(len(str(x)), len(str(y)))n_2 = n // 2x1, x2 = divmod(x, 10**n_2)y1, y2 = divmod(y, 10**n_2)# Conquerp1 = karatsuba(x1, y1)p2 = karatsuba(x2, y2)p3 = karatsuba((x1 + x2), (y1 + y2)) - p1 - p2# Combineresult = p1 * 10**(2*n_2) + p3 * 10**n_2 + p2return resultprint(karatsuba(1234, 5678)) # 7006652print(karatsuba(15, 60)) # 900print(karatsuba(987654, 123456)) # 121931812224
We understood the Karatsuba algorithm, a fast divide-and-conquer algorithm for multiplying two numbers. The algorithm is significantly faster than the traditional multiplication algorithms, especially for very large values of
Free Resources