Skip to content

Instantly share code, notes, and snippets.

@kiriappeee
Last active August 29, 2015 14:00
Show Gist options
  • Save kiriappeee/11395564 to your computer and use it in GitHub Desktop.
Save kiriappeee/11395564 to your computer and use it in GitHub Desktop.
Quick implementation of the Karatsuba multiplication algorithm
"""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