Peasant Multiplication

Here’s my entry for the The Daily WTF‘s Programming Praxis: Russian Peasant Multiplication:

function peasant1(a, b) {
  var value = a & 1 ? b : 0;
  while(a > 1) {
    a >>= 1;
    b <<= 1;
    if (a & 1)
      value += b;
  }
  return value;
}

function peasant2(a, b) {
  var value = a & 1 ? b : 0;
  if(a > 1)
    value += peasant2(a >> 1, b << 1);
  return value;
}

function peasant3(a, b) {
  return a > 1 ? (a & 1 ? b : 0) + peasant3(a >> 1, b << 1) : a & 1 ? b : 0;
}

function peasant4(a, b) {
  return a & 1 ? value = a > 1 ? value = b + peasant4(a >> 1, b << 1) : b : value = peasant4(a >> 1, b << 1);
}

Leave a Reply

Your email address will not be published. Required fields are marked *