簡體   English   中英

Python中的Karatsuba算法

[英]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

一些提示:

  • 我不認為您對ab價值觀是您想要的
  • 一個常見的錯誤通常是split不會返回嚴格較小的數字:請提供_least_significant_digits_right_shift
  • 當您輸入的一個長度為1而不是另一個長度時,會發生什么? 在這種情況下,分割返回1位數字是什么?

我正在計算要傳入的數字的最大長度,用這種方法固定了它。

   n = max(len(self.digits),len(other.digits))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM