Skip to content

Instantly share code, notes, and snippets.

@LPMatrix
Last active April 11, 2021 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LPMatrix/3b9b75b7f943ce2aabeaf7b3a62ad1e8 to your computer and use it in GitHub Desktop.
Save LPMatrix/3b9b75b7f943ce2aabeaf7b3a62ad1e8 to your computer and use it in GitHub Desktop.
import math
def karatsuba(x, y):
if x < 10 and y < 10:
return x * y
n = max(len(str(x)), len(str(y)))
m = int(math.ceil(float(n) / 2))
# divide x into two half
xh = int(math.floor(x / 10 ** m))
xl = int(x % (10 ** m))
# divide y into two half
yh = int(math.floor(y / 10 ** m))
yl = int(y % (10 ** m))
# Karatsuba's algorithm.
s1 = karatsuba(xh, yh)
s2 = karatsuba(yl, xl)
s3 = karatsuba(xh + xl, yh + yl)
s4 = s3 - s2 - s1
return int(s1 * (10 ** (m*2)) + s4 * (10 ** m) + s2)
print(karatsuba(3141592653589793238462643383279502884197169399375105820974944592, 2718281828459045235360287471352662497757247093699959574966967627))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment