【问题标题】:the implementation of the Karatsuba algorithm, the method only counts the small numbers true, but the big answer is not correct, what's the problem?Karatsuba算法的实现,该方法只计算小数为真,但大答案不正确,有什么问题?
【发布时间】:2019-01-15 15:23:36
【问题描述】:

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));

【问题讨论】:

  • 欢迎来到 StackOverflow!请将您的实际代码添加到问题中,而不是代码的屏幕截图。谢谢!

标签: javascript algorithm bigint karatsuba


【解决方案1】:

调用Math.pow 非常可疑。根据documentation,它

返回一个依赖于实现的近似值,将 x 提高到 y 次方的结果。

您不希望在 Karatzuba 中使用任何 近似值

【讨论】:

    【解决方案2】:
    return BigInt(parseInt(x) * parseInt(y));
    

    在构造 BigInt 之前将大的事物相乘,这违背了这一点。

    【讨论】:

    • (我想我明白你的意思,但是当 both 因素小于两位数时使用引用的代码(我的书不大)。但是,有使用* 运算符进行缩放……)
    【解决方案3】:

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

    您使用m2 拆分数字,但m(也)用于在组合之前/组合/“(多项式)评估”之前进行缩放。

    你需要使用2*m2

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 2020-08-17
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      相关资源
      最近更新 更多