Last active
July 11, 2020 18:12
-
-
Save blacktrub/f34589d757deb727bd47330588f5ec25 to your computer and use it in GitHub Desktop.
karatsuba algorithm
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
| import math | |
| def karatsuba(x, y): | |
| if (x < 10) and (y < 10): | |
| return x * y | |
| n = max(len(str(x)), len(str(y))) | |
| n2 = int(math.ceil(float(n) / 2)) | |
| a = int(math.floor(x / 10 ** n2)) | |
| b = int(x % (10 ** n2)) | |
| c = int(math.floor(y / 10 ** n2)) | |
| d = int(y % (10 ** n2)) | |
| p = a + b | |
| q = c + d | |
| ac = karatsuba(a, c) | |
| bd = karatsuba(b, d) | |
| pq = karatsuba(p, q) | |
| adbc = pq - ac - bd | |
| return 10 ** n * ac + 10 ** n2 * adbc + bd | |
| if __name__ == '__main__': | |
| result = karatsuba(5678, 1234) | |
| assert result == 5678 * 1234 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment