Created
September 27, 2021 14:28
-
-
Save mkhuzaima/26645b7b4994dcfb3f888f3dde797f45 to your computer and use it in GitHub Desktop.
This gist contains the famous algorithm "karatsuba" in python which is used to efficiently multiply two numbers.
This file contains 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 multiply(x, y): | |
n = len(str(x)) | |
if n == 1: | |
return x * y | |
nby2 = n // 2 | |
ten_to_nby2 = 10 ** nby2 | |
a = x // ten_to_nby2 | |
b = x % ten_to_nby2 | |
c = y // ten_to_nby2 | |
d = y % ten_to_nby2 | |
ac = multiply(a, c) | |
bd = multiply(b, d) | |
ad_plus_bc = multiply(a + b, c + d) - ac - bd | |
product = (ac * ten_to_nby2**2) + (ad_plus_bc * ten_to_nby2) + bd | |
return product | |
def integerInput(n): | |
try: | |
return int(input(f"Enter the number {n}: ")) | |
except: | |
return 0 | |
import time | |
a = integerInput(1) | |
b = integerInput(2) | |
start = time.time() | |
print(multiply(a, b)) | |
end = time.time() | |
print(f"The total time taken is : {end - start} ms") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment