mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-19 00:37:02 +00:00
Create karatsuba.py (#1309)
* Create karatsuba.py Added karatsuba algorithm for multiplication of two numbers * Update karatsuba.py Added doctests and divmod * Update karatsuba.py
This commit is contained in:
parent
e80d248e65
commit
61f7f94fde
31
maths/karatsuba.py
Normal file
31
maths/karatsuba.py
Normal file
|
@ -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
|
||||||
|
"""
|
||||||
|
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()
|
Loading…
Reference in New Issue
Block a user