Skip to content

Instantly share code, notes, and snippets.

@jinwoo1225
Created May 31, 2021 04:16
Show Gist options
  • Save jinwoo1225/0e9414b9d08f7ae3c5066ae3f6f585e6 to your computer and use it in GitHub Desktop.
Save jinwoo1225/0e9414b9d08f7ae3c5066ae3f6f585e6 to your computer and use it in GitHub Desktop.
karatsuba
def karatsuba(x: int, y: int) -> int:
# get Length of variable
x_str, y_str = str(x), str(y)
x_len, y_len = len(x_str), len(y_str)
# Initialize
if x_len == 1 or y_len == 1:
return x * y
# Divide
m = min(x_len, y_len) // 2
a, b = int(x_str[:-m]), int(x_str[-m:])
c, d = int(y_str[:-m]), int(y_str[-m:])
# Conquer
ac = karatsuba(a, c)
bd = karatsuba(b, d)
ad_bc = karatsuba(a + b, c + d) - ac - bd
# Combine
return 10 ** (2 * m) * ac + 10 ** m * ad_bc + bd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment