Sub topic 13
Karatsuba: Multiplying with Three Subproblems Instead of Four
This chapter assumes you can apply the master theorem, read recursive Python, and know that the grade-school method multiplies two n-digit numbers in O(n²) time.
Splitting a Number in Half
To multiply two large integers x and y, split each one at bit position m:
- x = a·2^m + b
- y = c·2^m + d
Here a and c are the high halves, and b and d are the low halves. Expanding the product gives:
xy = ac·2^(2m) + (ad + bc)·2^m + bd
Shifts and additions cost O(n). A direct recursive version computes four half-size products: ac, ad, bc, and bd. Its recurrence is T(n) = 4T(n/2) + O(n). Since log₂4 = 2 and n² dominates n, the master theorem gives O(n²). That is no improvement over the grade-school method.
The Trick: Reuse Two Products
Anatoly Karatsuba noticed that the middle term does not need ad and bc separately. It needs only their sum:
ad + bc = (a + b)(c + d) − ac − bd
You already need ac and bd for the outer terms. So one more product, (a + b)(c + d), gives you the middle term through two subtractions. That makes three recursive multiplications instead of four.
Implementation
def karatsuba(x, y):
# Multiplies non-negative integers x and y
if x < 10 or y < 10:
return x * y
m = max(x.bit_length(), y.bit_length()) // 2
hi_x, lo_x = x >> m, x & ((1 << m) - 1)
hi_y, lo_y = y >> m, y & ((1 << m) - 1)
z0 = karatsuba(lo_x, lo_y)
z2 = karatsuba(hi_x, hi_y)
z1 = karatsuba(lo_x + hi_x, lo_y + hi_y) - z0 - z2
return (z2 << (2 * m)) + (z1 << m) + z0
print(karatsuba(1234, 5678) == 1234 * 5678) # TrueThe shift x >> m extracts the high half, and the mask x & ((1 << m) - 1) keeps the low m bits. The base case falls back to the built-in multiplication once either operand is small.
Analysis
The new recurrence is T(n) = 3T(n/2) + O(n). Here a = 3 and b = 2, so n^(log₂3) ≈ n^1.585. That grows faster than the O(n) combine cost, so case 1 of the master theorem applies and gives T(n) = O(n^1.585).
| Method | Recurrence | Running time |
|---|---|---|
| Naive split | 4T(n/2) + O(n) | O(n²) |
| Karatsuba | 3T(n/2) + O(n) | O(n^1.585) |
Each level of recursion replaces one multiplication with a few additions. Additions cost linear time, while the saved multiplication would branch into its own subtree, so the trade pays off at every level.
Exercise
Suppose you found a way to multiply using five subproblems of one-third size plus O(n) work. Is this faster than Karatsuba?
Show answer
The recurrence is T(n) = 5T(n/3) + O(n), so T(n) = O(n^(log₃5)), which is about O(n^1.465). That is faster than Karatsuba's O(n^1.585).
Exercise
Using decimal halves with m = 2 digits, compute 1234 × 5678 by hand with Karatsuba's three products.
Show answer
a = 12, b = 34, c = 56, d = 78. ac = 672, bd = 2652, (a+b)(c+d) = 46 × 134 = 6164, so the middle term is 6164 − 672 − 2652 = 2840. The result is 672·10⁴ + 2840·10² + 2652 = 6720000 + 284000 + 2652 = 7006652.