Skip to content

Instantly share code, notes, and snippets.

@marcossevilla
Last active October 26, 2020 15:32
Show Gist options
  • Save marcossevilla/6eb7ccfe959cd330b28011ed73507017 to your computer and use it in GitHub Desktop.
Save marcossevilla/6eb7ccfe959cd330b28011ed73507017 to your computer and use it in GitHub Desktop.
Karatsuba Multiplication with Bitwise operators for memory efficiency
def karatsuba(x, y):
if x < 16 or y < 16:
return x * y
max_len = max(x.bit_length(), y.bit_length()) // 2
bitwise_filter = (1 << max_len) - 1
a, b = x >> max_len, x & bitwise_filter
c, d = y >> max_len, y & bitwise_filter
ac = karatsuba(a, c)
bd = karatsuba(b, d)
abcd = karatsuba(a+b, c+d) - ac - bd
return (((ac << max_len) + abcd) << max_len) + bd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment