Skip to content

Instantly share code, notes, and snippets.

@guilhermefgs
Created January 11, 2025 02:20
Show Gist options
  • Save guilhermefgs/6ea263cb61e945f56ef51baf339a6f9e to your computer and use it in GitHub Desktop.
Save guilhermefgs/6ea263cb61e945f56ef51baf339a6f9e to your computer and use it in GitHub Desktop.
Karatsuba Algorithm for Integer Multiplication - Not 100%
def karatsuba_integer_multiplier(int1: str, int2: str) -> int:
"""
Assumptions:
- int1 and int2 initially handled as strings
- int1 and int2 have the same size
- int1 and int2 have even digit numbers
"""
n = len(int1)
print(n)
if n == 2 or n == 3:
return int(int1) * int(int2)
m = n // 2
a,b,c,d = int1[:m], int1[m:], int2[:m], int2[m:]
print(a,b,c,d, m)
ac = karatsuba_integer_multiplier(a,c)
bd = karatsuba_integer_multiplier(b,d)
a_b = str(int(a)+int(b))
c_d = str(int(c)+int(d))
ab_cd = karatsuba_integer_multiplier(a_b,c_d) - ac - bd # FIXME a+b not defined
return 10**n * ac + 10**(n//2) * ab_cd + bd
int1 = "5678"
int2 = "1234"
print(karatsuba_integer_multiplier(int1, int2))
int1 = "3141592653589793238462643383279502884197169399375105820974944592"
int2 = "2718281828459045235360287471352662497757247093699959574966967627"
print(str(karatsuba_integer_multiplier(int1, int2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment