Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That reminds me of the classic and occasionally useful multiplication algorithm.

  mult(x,y):
  int total = 0;
  do
  {
  if (x & 1) total += y;  // if x's last bit is true add y
  x = x >> 1; //binary shift right 1 to divide x by 2.
  y = y << 1; //binary shift left 1 to multiply y by 2.
  }while (x > 0);
  return total;
which I tend to use as an intro to algorithms because it's useful and short. But, just complex enough to think about.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: