1

Hi I am trying to implement karatsuba algorithm in Javascript. As of now the algorithm works fine for certain cases like when the length of integer is 4 or 8.When the length of integer is 6 it prints out wrong result

Eg: 3141*2718=>8537238 (correct result)

Eg: 314*271=>84981.37398106341 (incorrect result)

Eg: 3141592653589793238462643383279502884197169399375105820974944592 * 2718281828459045235360287471352662497757247093699959574966967627 =>8.539734222673569e+126 (partially correct )

var firstnumber= 3141592653589793238462643383279502884197169399375105820974944592
var secondNumber=2718281828459045235360287471352662497757247093699959574966967627



Karatsuba(firstnumber,secondNumber)


function Karatsuba(x,y)
{

    if(x<10 || y<10)
    {

        return x*y
    }




var first=Math.ceil(Math.log(x + 1) / Math.LN10)
var  second=Math.ceil(Math.log(x + 1) / Math.LN10)





 var min=Math.min(first,second);






var a=Math.floor(x/Math.pow(10,min/2))
var b=Math.floor(x%Math.pow(10,min/2))
var c=Math.floor(y/Math.pow(10,min/2))
var d=Math.floor(y%Math.pow(10,min/2))


 var s=Math.pow(10,min/2)

 return ((Math.pow(10,min))*Karatsuba(a,c)+ s*(Karatsuba(a,d) +Karatsuba(b,c)) +  Karatsuba(b,d))
}
Sheildboy
  • 89
  • 7

1 Answers1

1

This can be not the only reason for your results to be incorrect, but in javascript, all numbers are fixed-precision floating-point numbers, and with big numbers (more than 15 digits) you will meet the lack of precision, that will bring to incorrect results. But that not explains why it is incorrect for relatively small numbers (6 digits integer can be perfectly represented both as float and double)

Roman Svistunov
  • 1,069
  • 6
  • 11