mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-05 02:40:16 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
33 lines
645 B
Python
33 lines
645 B
Python
"""Multiply two numbers using Karatsuba algorithm"""
|
|
|
|
|
|
def karatsuba(a: int, b: int) -> int:
|
|
"""
|
|
>>> 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
|
|
|
|
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()
|