Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Created November 26, 2022 05:05
Show Gist options
  • Save Per48edjes/1b35103fb19cbe427dabe93a4aff6c1b to your computer and use it in GitHub Desktop.
Save Per48edjes/1b35103fb19cbe427dabe93a4aff6c1b to your computer and use it in GitHub Desktop.
Recursive Python implementation of Karatsuba multiplication
#!/usr/bin/env python3
def karatsuba_mul(m: int, n: int) -> int:
"""
Implementation of recursive Karatsuba multiplication
>>> karatsuba_mul(56, 12)
672
>>> karatsuba_mul(78, 34)
2652
>>> karatsuba_mul(56 + 78, 12 + 34)
6164
>>> karatsuba_mul(46, 134)
6164
>>> karatsuba_mul(5678, 1234)
7006652
>>> karatsuba_mul(1234, 5678)
7006652
>>> karatsuba_mul(4, 1441)
5764
>>> karatsuba_mul(23847, 3498)
83416806
"""
if m // 10 == 0 and n // 10 == 0:
return m * n
else:
k = max(map(lambda i: len(str(i)), (m, n))) // 2
a, b = m // (10**k), m % (10**k)
c, d = n // (10**k), n % (10**k)
ac, bd = karatsuba_mul(a, c), karatsuba_mul(b, d)
bc_plus_ad = karatsuba_mul(a + b, c + d) - ac - bd
return (ac * (10 ** (2 * k))) + (bc_plus_ad * (10**k)) + bd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment