2024-03-13 06:52:41 +00:00
|
|
|
"""Multiply two numbers using Karatsuba algorithm"""
|
2019-10-08 12:25:50 +00:00
|
|
|
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2023-10-05 12:30:43 +00:00
|
|
|
def karatsuba(a: int, b: int) -> int:
|
2019-10-08 12:25:50 +00:00
|
|
|
"""
|
|
|
|
>>> karatsuba(15463, 23489) == 15463 * 23489
|
|
|
|
True
|
|
|
|
>>> karatsuba(3, 9) == 3 * 9
|
|
|
|
True
|
|
|
|
"""
|
|
|
|
if len(str(a)) == 1 or len(str(b)) == 1:
|
2019-10-22 17:13:48 +00:00
|
|
|
return a * b
|
2019-10-08 12:25:50 +00:00
|
|
|
|
2022-10-27 20:51:14 +00:00
|
|
|
m1 = max(len(str(a)), len(str(b)))
|
|
|
|
m2 = m1 // 2
|
2019-10-08 12:25:50 +00:00
|
|
|
|
2022-10-27 20:51:14 +00:00
|
|
|
a1, a2 = divmod(a, 10**m2)
|
|
|
|
b1, b2 = divmod(b, 10**m2)
|
2019-10-08 12:25:50 +00:00
|
|
|
|
2022-10-27 20:51:14 +00:00
|
|
|
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)
|
2019-10-08 12:25:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
print(karatsuba(15463, 23489))
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|