7

I am studying the fast square root algorithm by bit shift. I was stuck by the code from wikipedia.

short isqrt(short num) {
    short res = 0;
    short bit = 1 << 14; // The second-to-top bit is set: 1L<<30 for long

    // "bit" starts at the highest power of four <= the argument.
    while (bit > num)
        bit >>= 2;

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

I know it can generate the correct result, but how does it make it? I am especially confused by this sentence, res = (res >> 1) + bit; Why res should be divided by 2 here? Can anyone shed some light on this? Thank!

csrfengye
  • 71
  • 1
  • 1
  • 5
  • 1
    `>> 1` is a bit-wise right shift, e.g. "divide by 2". `>> 2` would be divide by 4, and `>> n` is "divide by 2**(n)" – Marc B Mar 21 '13 at 20:45
  • Can you explain why res is divided by 2 here? – csrfengye Mar 22 '13 at 02:37
  • Here you can find the explanation for your question http://stackoverflow.com/questions/10866119/what-is-the-fastest-way-to-find-integer-square-root-using-bit-shifts?rq=1 – Rd7 Apr 09 '13 at 14:54
  • 1
    Does this answer your question? [What is the fastest way to find integer square root using bit shifts?](https://stackoverflow.com/questions/10866119/what-is-the-fastest-way-to-find-integer-square-root-using-bit-shifts) – S.S. Anne Apr 12 '20 at 01:38

0 Answers0