Skip to content

Instantly share code, notes, and snippets.

@blacktrub
Last active July 11, 2020 18:12
Show Gist options
  • Select an option

  • Save blacktrub/f34589d757deb727bd47330588f5ec25 to your computer and use it in GitHub Desktop.

Select an option

Save blacktrub/f34589d757deb727bd47330588f5ec25 to your computer and use it in GitHub Desktop.
karatsuba algorithm
import math
def karatsuba(x, y):
if (x < 10) and (y < 10):
return x * y
n = max(len(str(x)), len(str(y)))
n2 = int(math.ceil(float(n) / 2))
a = int(math.floor(x / 10 ** n2))
b = int(x % (10 ** n2))
c = int(math.floor(y / 10 ** n2))
d = int(y % (10 ** n2))
p = a + b
q = c + d
ac = karatsuba(a, c)
bd = karatsuba(b, d)
pq = karatsuba(p, q)
adbc = pq - ac - bd
return 10 ** n * ac + 10 ** n2 * adbc + bd
if __name__ == '__main__':
result = karatsuba(5678, 1234)
assert result == 5678 * 1234
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment