2
所以我实现在Python Karatsuba的乘算法。现在我有无限递归,无法解决它。有任何想法吗?如果需要,我会提供更多的代码。karatsuba算法在Python
def multiply(self, other):
# helper function
def split(largeInt, n):
least = largeInt._least_significant_digits(n/2)
most = largeInt._right_shift(n/2)
if debug: assert least.to_int() + (most.to_int() << (LargeInt.base_bits*(n/2))) == largeInt.to_int()
return least, most
n = max(len(str(self)),len(str(other)))
if (n==1):
return self.to_int() * other.to_int()
else:
aR, aL = split(self,n)
bR , bL = split(other, n)
x1 = aL.multiply(bL)
x2 =aR.multiply(bR)
a = aL.add(bL)
b = aR.add(bR)
x3=a.multiply(b)
# code for recursive step here
#return 1 # change this line with your implementation
return x1 * 10**n + (x3-x1-x2) * 10**(n/2) + x2
的代码有像“TODO:你在这里实施”的意见和“代码基本情况在这里”在里面。它在实际的Karatsuba代码之前也有'return 2'。你在这里发布了正确的代码吗? –
此代码需要正确缩进。 – deebee
我看到你已经在代码中放置了一些诊断打印语句。他们展示了什么?一旦深入到无限递归中,什么值被传递给'multiply'?你确定你调用的大整数方法做你想要的吗?是'n/2'产生一个整数还是浮点数,如果后者不好? –