I am trying to implement Karatsuba Multiplication in Python. Unfortunately, my code is failing on 64 digit test cases (curriculum I am working on) because I start yielding negative numbers for my gauss calculations. I included my code below and was wondering if anyone would be able to offer some guidance what I may be missing.
Additionally, I am intentionally storing these large numbers as strings because the whole point of this assignment was to challenge myself calling recursion. I believe Python is able to handle these large numbers automatically, but it would defeat the whole challenging part of this assignment.
The input are both 64 digits.
def karatsuba(input1, input2):
first_number = len(input1)
second_number = len(input2)
# base case
if first_number <= 2:
return str(int(input1) * int(input2))
else:
# first half
# changing the divider from round(first_number/2) to first_number // 2 yielded different results.
if first_number % 2 == 1:
add_zero = first_number + 1
else:
add_zero = first_number
divider_a = first_number // 2
a = input1[:divider_a]
b = input1[divider_a:]
print("a: " + a)
print("b: " + b)
# second half
divider_b = second_number // 2
c = input2[:divider_b]
d = input2[divider_b:]
print("c: " + c)
print("d: " + d)
# recursive
ac = karatsuba(a, c)
print("ac: " + ac)
bd = karatsuba(b, d)
print("bd: " + bd)
ad = karatsuba(a, d)
print("ad: " + ad)
bc = karatsuba(b, c)
print("bc: " + bc)
# for subtraction, you add the negative.
def addition(input_a, input_b):
return str(int(input_a) + int(input_b))
ab_cd = karatsuba(addition(a, b), addition(c, d))
print("ab_cd: " + ab_cd)
gauss = addition(addition(ab_cd, "-"+ac), "-"+bd)
print("gauss: " + gauss)
merge1 = ac + "0"*add_zero
print("merge1: " + merge1)
merge2 = gauss + str(("0"*(add_zero//2)))
print("merge2: " + merge2)
merge3 = bd
return (addition(addition(merge1, merge2), merge3))
if __name__ == '__main__':
input_a, input_b = map(str, input().split())
print(karatsuba(input_a, input_b))