Algorithms · Visualized
Karatsuba Multiplication
Divide & Conquer
Break a problem into independent subproblems, solve each, and combine the answers.
Karatsuba multiplies two large numbers faster than the O(n²) grade-school method by splitting each into halves and combining three recursive multiplications (not four) via an algebraic identity — saving one multiplication at every level of recursion. Time: O(n^1.585) average, O(n^1.585) versus O(n²) grade-school worst; space: O(n) — recursive splits.
Big-O: Classic D&C recursions: Merge Sort, Quick Sort, Maximum Subarray, Fast Power.
Karatsuba Multiplication
Divide & ConquerKaratsuba multiplies two large numbers faster than the O(n²) grade-school method by splitting each into halves and combining three recursive multiplications (not four) via an algebraic identity — saving one multiplication at every level of recursion.
How Karatsuba Multiplication Works
- Split each n-digit number into halves: x = x1·10^(n/2) + x0, y = y1·10^(n/2) + y0.
- Recursively compute three products: a = x1·y1, b = x0·y0, and c = (x1+x0)·(y1+y0).
- Derive the cross term without a fourth multiplication: middle = c − a − b = x1·y0 + x0·y1.
- Combine: result = a·10^n + middle·10^(n/2) + b.
- Base case: when the numbers are small enough, multiply directly (addition z = Σ).
Karatsuba Multiplication Worked Example
Input: {x: 1234, y: 5678}
Split: x1=12, x0=34, y1=56, y0=78. a = 12·56 = 672; b = 34·78 = 2652; c = (12+34)·(56+78) = 46·134 = 6164. middle = 6164 − 672 − 2652 = 2840. result = 672·10^4 + 2840·10^2 + 2652 = 6720000 + 284000 + 2652 = 7006652, which matches 1234 × 5678.
def karatsuba(x, y):
if x < 10 or y < 10:
return x * y
n = max(len(str(x)), len(str(y)))
m = n // 2
a, b = divmod(x, 10 ** m)
c, d = divmod(y, 10 ** m)
ac = karatsuba(a, c)
bd = karatsuba(b, d)
adbc = karatsuba(a + b, c + d) - ac - bd
return ac * 10 ** (2 * m) + adbc * 10 ** m + bdBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Karatsuba Multiplication Time & Space Complexity
When to Use Karatsuba Multiplication
- Big-integer libraries (arbitrary precision arithmetic).
- Cryptographic computations on large numbers.
- Polynomial multiplication (same divide-and-conquer trick).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.