Last active
August 29, 2015 14:24
-
-
Save csarigoz/8577b7b5d7475ef25c33 to your computer and use it in GitHub Desktop.
A Basic Recursive Integer Multiplication Algorithm
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 recursive_mult(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 = recursive_mult(a,c) | |
ad = recursive_mult(a,d) | |
bc = recursive_mult(b,c) | |
bd = recursive_mult(b,d) | |
return (10**(2*m2))*ac + (10**m2)*ad+ (10**m2)*(bc) + bd | |
for i in range(10): | |
x = randint(1,10000) | |
y = randint(1,10000) | |
expected = x * y | |
result = recursive_mult(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