我正在尝试在 Python 中实现 Karatsuba 乘法。不幸的是,我的代码在 64 位测试用例(我正在研究的课程)上失败了,因为我开始为我的高斯计算产生负数。我在下面包含了我的代码,并想知道是否有人能够提供一些我可能缺少的指导。
此外,我有意将这些大数字存储为字符串,因为这项任务的全部目的是挑战自己调用递归。我相信 Python 能够自动处理这些大数字,但它会打败这项任务的整个具有挑战性的部分。
输入均为 64 位数字。
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))