2

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?

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));
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • 2
    Welcome to StackOverflow! Please add your actual code to the question rather than a screenshot of your code. Thank you! – Nick Jan 15 '19 at 15:24

3 Answers3

1

Invoking Math.pow is very suspicious. According to documentation, it

Returns an implementation-dependent approximation to the result of raising x to the power y.

You don't want any approximations in Karatzuba.

user58697
  • 7,808
  • 1
  • 14
  • 28
1
return BigInt(parseInt(x) * parseInt(y));

It defeats the point to multiply large things together before constructing a BigInt.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • (I think I see your point, but the code quoted is used when *both* factors are shorter than two digits (not large by my book). But then, there is scaling using the `*` operator …) – greybeard Jan 16 '19 at 01:29
0

In addition to user58697's word of warning about floating point arithmetic in general and transcendental functions in particular:

You use m2 in splitting the numbers, but m (too) in scaling before/in combination/"(polynomial) evaluation".

You need to use 2*m2.

greybeard
  • 2,249
  • 8
  • 30
  • 66