在实施Karatsuba算法时,该方法只计算了少量的数字,但是较大的答案是不正确的,这是什么问题?

时间:2019-01-15 15:23:36

标签: javascript algorithm bigint karatsuba

Karatsuba算法的实现,该方法只计算了少量的数字,但是大的答案不正确,这是什么问题?

var x = "1685287499328328297814655639278583667919355849391453456921116729";
var y = "7114192848577754587969744626558571536728983167954552999895348492";

function karatsuba(x, y) {
    if (x.length < 2 && y.length < 2) {
        return BigInt(parseInt(x) * parseInt(y));
    }
    var m = Math.min(x.length, y.length);
    var m2 = m / 2;
    var a = BigInt(x.substring(0, m2));
    var b = BigInt(x.substring(m2));
    var c = BigInt(y.substring(0, m2));
    var d = BigInt(y.substring(m2));
    var ac = a * c;
    var bd = b * d;
    var sum = (a + b) * (c + d) - ac - bd;

    return BigInt(Math.pow(10, m)) * ac + BigInt(Math.pow(10, m2)) * sum + bd;
}

console.log(karatsuba(x, y));

3 个答案:

答案 0 :(得分:1)

调用Math.pow非常可疑。根据{{​​3}},

  

返回将x提高到y的结果的实现相关近似。

您不希望卡尔祖巴有任何近似值

答案 1 :(得分:1)

c = webdriver.Chrome()
c.get(some_url)

element = c.find_element_by_tag_name('body') # or whatever tag you're looking to scrape from

for i in range(10):
    element.send_keys(Keys.END)
    time.sleep(1)

soup = BeautifulSoup(c.page_source, 'html.parser')

它克服了在构造BigInt之前将大型事物相乘的观点。

答案 2 :(得分:0)

除了user58697's word of warning about floating point arithmetic in general and transcendental functions in particular

您使用m2进行数字分割,但使用m(过分)在/组合/“(多项式)求值”之前进行缩放。

  

您需要使用2*m2