Created
July 15, 2015 03:49
-
-
Save csarigoz/517fea09d410baa1829c to your computer and use it in GitHub Desktop.
Karatsuba Algortihm for Integer Multiplication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import randint | |
def karatsuba(x, y): | |
if (x<10) or (y<10): | |
return x*y | |
x_str = str(x) | |
x_n = len(x_str) | |
y_str = str(y) | |
y_n = len(y_str) | |
m = max(x_n, y_n) | |
m2 = int(m/2) | |
a = int(x_str[:-m2]) | |
b = int(x_str[-m2:]) | |
c = int(y_str[:-m2]) | |
d = int(y_str[-m2:]) | |
ac = karatsuba(a,c) | |
bd = karatsuba(b,d) | |
abcd = karatsuba((a+b),(c+d)) | |
return (10**(2*m2))*ac + (10**m2)*(abcd-ac-bd) + bd | |
for i in range(10): | |
x = randint(1,10000) | |
y = randint(1,10000) | |
expected = x * y | |
result = karatsuba(x, y) | |
print ("%d and %d:" % (x,y)) | |
print ('expected: ', expected) | |
print ('actual: ', result) | |
if result != expected: | |
print ("Error with: " + str(x) + " " + str(y)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment