Skip to content

Instantly share code, notes, and snippets.

@mkhuzaima
Created September 27, 2021 14:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkhuzaima/26645b7b4994dcfb3f888f3dde797f45 to your computer and use it in GitHub Desktop.
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.
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