square root by bit shift

csrfengye picture csrfengye · Mar 21, 2013 · Viewed 9.8k times · Source

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!

Answer