Skip to content
This repository has been archived by the owner on Mar 28, 2023. It is now read-only.

Karatsuba Multiplication #7

Open
nitin42 opened this issue Jan 25, 2017 · 4 comments
Open

Karatsuba Multiplication #7

nitin42 opened this issue Jan 25, 2017 · 4 comments

Comments

@nitin42
Copy link

nitin42 commented Jan 25, 2017

Can provide the code for karatsuba multiplication (<=20 lines).

@ovidiuch
Copy link
Owner

ovidiuch commented Jan 25, 2017

Sounds good. I'll keep the thread open if you post it here and label it with something like visualisation needed.

@nitin42
Copy link
Author

nitin42 commented Jan 25, 2017

Here is the code

function karatsubaMulti(x, y) {
  let n = Math.min(('' + x).length, ('' + y).length); // Implicit coercision

  if(n == 1)
    return x * y;

  let bm = Math.pow(10, parseInt(n / 2));
  let bm2 = Math.pow(10, 2 * parseInt(n / 2));
  let a = parseInt(x / bm);
  let b = x % bm;
  let c = parseInt(y / bm);
  let d = y % bm;

  let caller = arguments.callee; // For recursive call, not using TCO
  return bm2 * caller(a, c) + bm * (caller(a, d) + caller(b, c)) + caller(b, d);
}
let a = karatsubaMulti(12345, 6789);
console.log(a); // 83810205

Works fine but exceeds the maximum call stack size when arrow functions are used instead.

@vmasto
Copy link

vmasto commented Feb 14, 2017

Just a heads up that arguments.callee is not allowed in strict mode.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee

@nitin42
Copy link
Author

nitin42 commented Feb 16, 2017

Oh ! Thanks for pointing this. I'll rewrite the code 😄

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants