Sunday, November 27, 2011

Karatsuba algorithm


Key of the Process

The basic step of Karatsuba's algorithm is a formula that allows us to compute the product of two large numbers x and y using three multiplications of smaller numbers, each with about half as many digits as x or y, plus some additions and digit shifts.
Let x and y be represented as n-digit strings in some base B. For any positive integer m less than n, one can split the two given numbers as follows
x = x1Bm + x0
y = y1Bm + y0
where x0 and y0 are less than Bm. The product is then
xy = (x1Bm + x0)(y1Bm + y0)
z2 B2m + z1 Bm + z0
where
z2 = x1y1
z1 = x1y0 + x0y1
z0 = x0y0.

Example

To compute the product of 1234 and 5678, choose B = 10 and m = 2. Then
12 34 = 12 × 102 + 34
56 78 = 56 × 102 + 78
z2 = 12 × 56 = 672
z0 = 34 × 78 = 2652
z1 = (12 + 34)(56 + 78) - z2 - z0 = 46 × 134 - 672 - 2652 = 2840
result = z2 × 102×2 + z1 × 102 + z0 = 672 × 10000 + 2840 × 100 + 2652 = 7006652.

No comments:

Post a Comment