Last active
August 29, 2015 14:00
-
-
Save kiriappeee/11395564 to your computer and use it in GitHub Desktop.
Quick implementation of the Karatsuba 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
"""Quick implementation of the Karatsuba multiplication algorithm while doing | |
the Stanford Algortihms Design and Analysis Part 1 Course""" | |
def karatsuba(x,y): | |
if x < 10 and y < 10: | |
return x*y | |
else: | |
if x > y: | |
divider = pow(10,len(str(x)) / 2) | |
else: | |
divider = pow(10,len(str(y)) / 2) | |
a = x // divider | |
b = x % divider | |
c = y // divider | |
d = y % divider | |
ac = karatsuba(a,c) | |
bd = karatsuba(b,d) | |
e = a+b | |
f = c+d | |
ef = karatsuba(e,f) | |
return (ac*pow(divider,2) + bd + ((ef-bd-ac)*divider)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment