Skip to content

Create karatsuba.py #1309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 8, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions maths/karatsuba.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
""" Multiply two numbers using Karatsuba algorithm """

def karatsuba(a, b):
"""
>>> karatsuba(15463, 23489) == 15463 * 23489
True
>>> karatsuba(3, 9) == 3 * 9
True
"""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True

if len(str(a)) == 1 or len(str(b)) == 1:
return (a * b)
else:
m1 = max(len(str(a)), len(str(b)))
m2 = m1 // 2

a1, a2 = divmod(a, 10**m2)
b1, b2 = divmod(b, 10**m2)

x = karatsuba(a2, b2)
y = karatsuba((a1 + a2), (b1 + b2))
z = karatsuba(a1, b1)

return ((z * 10**(2*m2)) + ((y - z - x) * 10**(m2)) + (x))


def main():
print(karatsuba(15463, 23489))


if __name__ == "__main__":
main()