[英]Karatsuba algorithm in Python
所以我正在用python實現Karatsuba的乘法算法。 現在,我有無限遞歸,無法解決。 有任何想法嗎? 如果需要,我將提供更多代碼。
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
一些提示:
a
, b
價值觀是您想要的 。 _least_significant_digits
, _right_shift
。 我正在計算要傳入的數字的最大長度,用這種方法固定了它。
n = max(len(self.digits),len(other.digits))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.