Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise integer cube root algorithm

Here is a simple way to calculate an integer square root:

int isqrt(int num)
{
    int root=0;
    int b = 0x8000;
    int a=0, c=0;

    while (b) {
        c = a|b;

        if (c*c <= num)
            a |= b;   

        b >>= 1;
    }       
}

Ingeniously (thanks Wikipedia), this can be optimised like this:

int sqrt(short num)
{
    int op = num;
    int res = 0;
    int one = 1 << 30;

    while (one > op)
        one >>= 2;

    while (one != 0) {
        if (op >= res + one) {
            op -= res + one;
            res = (res >> 1) + one;
        }
        else
          res >>= 1;
        one >>= 2;
    }
    return res;
}

My question: Can a similarly optimised algorithm be written for an integer cube root? (This is to be run on a small microcontroller which prefers not to do multiplications)

like image 876
Rocketmagnet Avatar asked Jul 10 '11 13:07

Rocketmagnet


1 Answers

According to this SO question and to the answer marked, from the Hacker's Delight book you can find this implementation:

int icbrt2(unsigned x) {
   int s;
   unsigned y, b, y2;

   y2 = 0;
   y = 0;
   for (s = 30; s >= 0; s = s - 3) {
      y2 = 4*y2;
      y = 2*y;
      b = (3*(y2 + y) + 1) << s;
      if (x >= b) {
         x = x - b;
         y2 = y2 + 2*y + 1;
         y = y + 1;
      }
   }
   return y;
}
like image 190
Jack Avatar answered Sep 22 '22 05:09

Jack