Created
September 5, 2020 11:12
-
-
Save raeq/1097776aaa37010f71948562ae9a70ef to your computer and use it in GitHub Desktop.
Karatsuba fast multiplication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def karatsuba_fast_multiply(multiplier: int, multiplicand: int) -> int: | |
""" | |
Karatsuba fast multiplication, published in 1962 | |
https://en.wikipedia.org/wiki/Karatsuba_algorithm | |
Args: | |
x (): | |
y (): | |
Returns: int | |
>>> karatsuba_fast_multiply(2, 4) | |
8 | |
>>> karatsuba_fast_multiply(55561165165163231656, 4649494651616619847) | |
258331340273014094289730553689748276632 | |
""" | |
# only use this method for very large values of x or y | |
if multiplier.bit_length() <= 1536 or multiplicand.bit_length() <= 1536: | |
return multiplier * multiplicand | |
else: | |
n = max(multiplier.bit_length(), multiplicand.bit_length()) | |
half = (n + 32) // 64 * 32 | |
mask = (1 << half) - 1 | |
x_low = multiplier & mask | |
y_low = multiplicand & mask | |
x_high = multiplier >> half | |
y_high = multiplicand >> half | |
high = karatsuba_fast_multiply(x_high, y_high) | |
high_times_low = karatsuba_fast_multiply(x_low + x_high, y_low + y_high) | |
low = karatsuba_fast_multiply(x_low, y_low) | |
reduced = high_times_low - high - low | |
return (((high << half) + reduced) << half) + c | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment