Skip to content

Instantly share code, notes, and snippets.

@haocong
Last active December 22, 2018 19:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haocong/c2d9b2169d28eb15a94d to your computer and use it in GitHub Desktop.
Save haocong/c2d9b2169d28eb15a94d to your computer and use it in GitHub Desktop.
Karatsuba Multiplication in JavaScript
/**
* Karatsuba Multiplication
* @param {Number} x - first number
* @param {Number} y - second number
* @return {Number} Multiply of x and y
*/
function karatsubaMulti(x, y) {
let n = Math.min(('' + x).length, ('' + y).length);
if(n == 1)
return x * y;
let tenpowhalfn = Math.pow(10, parseInt(n / 2));
let tenpown = Math.pow(10, 2 * parseInt(n / 2));
let a = parseInt(x / tenpowhalfn);
let b = x % tenpowhalfn;
let c = parseInt(y / tenpowhalfn);
let d = y % tenpowhalfn;
let caller = arguments.callee;
return tenpown * caller(a, c) + tenpowhalfn * (caller(a, d) + caller(b, c)) + caller(b, d);
}
@haocong
Copy link
Author

haocong commented Mar 8, 2016

Usage

karatsubaMulti(1234, 56789) // return 70077626

@BrentonCozby
Copy link

BrentonCozby commented Aug 17, 2017

could you please explain why you round down the exponent when calculating the tenpown and tenpowhalfn? and why you take the minimum digit length for n? I'm assuming this is for when either of the digits lengths are odd, I just can't figure out why this works. Thanks for sharing this gist!

@Falieson
Copy link

Falieson commented May 27, 2018

IF you get the error

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

All you have to do is remove line 23, 'let caller = .... ' and change the return to

  return tenpown * karatsubaMulti(a, c)
    + tenpowhalfn * (karatsubaMulti(a, d)
    + karatsubaMulti(b, c))
    + karatsubaMulti(b, d)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment