簡體   English   中英

karatsuba的整數乘法算法python

[英]karatsuba's integer multiplication algorithm python

這段代碼沒有通過所有測試用例,有人可以幫忙嗎? 我只通過直截了當的測試,然后失去了精度。

import math
import unittest


class IntegerMultiplier:

    def multiply(self, x, y):
        if x < 10 or y < 10:
            return x * y

        x = str(x)
        y = str(y)

        m_max = min(len(x), len(y))
        x = x.rjust(m_max, '0')
        y = y.rjust(m_max, '0')

        m = math.floor(m_max / 2)

        x_high = int(x[:m])
        x_low = int(x[m:])

        y_high = int(y[:m])
        y_low = int(y[m:])

        z1 = self.multiply(x_high, y_high)
        z2 = self.multiply(x_low, y_low)
        z3 = self.multiply((x_low + x_high), (y_low + y_high))
        z4 = z3 - z1 - z2

        return z1 * (10 ** m_max) + z4 * (10 ** m) + z2


class TestIntegerMultiplier(unittest.TestCase):

    def test_easy_cases(self):
        integerMultiplier = IntegerMultiplier()

        case2 = integerMultiplier.multiply(2, 2)
        self.assertEqual(case2, 4)

        case3 = integerMultiplier.multiply(2, 20000)
        self.assertEqual(case3, 40000)

        case4 = integerMultiplier.multiply(2000, 2000)
        self.assertEqual(case4, 4000000)

    def test_normal_cases(self):
        intergerMultiplier = IntegerMultiplier()

        case1 = intergerMultiplier.multiply(1234, 5678)
        self.assertEqual(case1, 7006652)

if __name__ == '__main__':
    unittest.main()

對於第一個測試用例,'test_easy_cases'在其他兩種情況下都通過了,我得到了錯誤,例如AssertionError: 6592652 != 7006652

在選擇m ,可以為以下所有分解和合成選擇一個底數。 我建議使用長度表示形式,表示因子長度的平均值。
我不知道為什么要使用十進制數字一次又一次地實現Karatsuba乘法-您需要重新檢查兩個地方:

  • 將因子f分為高和低時,低需要為f mod m,高f // m
  • 在合成中( IntegerMultiplier.multiply()最后一個表達式),您需要堅持使用m (和2×m )-每次m_max IntegerMultiplier.multiply() ,使用m_max是錯誤的。

暫無
暫無

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

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