2
我正在研究通过位移快速平方根算法。我被来自维基百科的代码卡住了。平方根移位
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;
}
我知道它可以产生正确的结果,但它是如何做的?我特别困惑这句话, res =(res >> 1)+ bit; 为什么res在这里应该除以2? 任何人都可以对此有所了解吗?谢谢!
“1”是按位右移,例如, “除以2”。 '>> 2'会被4除,并且'>> n'被“除以2 **(n)” – 2013-03-21 20:45:21
你能解释为什么res在这里被2除? – csrfengye 2013-03-22 02:37:15
在这里你可以找到你的问题的解释 http://stackoverflow.com/questions/10866119/what-is-the-fastest-way-to-find-integer-square-root-using-bit-shifts? rq = 1 – Rd7 2013-04-09 14:54:01