预先说明:应该注意,能够将sqrt作为机器指令执行的处理器将足够快.毫无疑问,它的(微)程序使用Newton-Raphson,并且该算法具有二次收敛性,每次迭代将精确数字的数量加倍.
因此,尽管这样的想法使用了很好的正方形等属性,但实际上并不值得追求(请参阅下一个建议).
// compute the root of the biggests square that is a power of two < n
public static int pcomp( int n ){
long p2 = 1;
int i = 0;
while( p2 < n ){
p2 <<= 2;
i += 2;
}
p2 >>= 2;
i -= 2;
return (int)(p2 >>= i/2);
}
public static int squareLowerThan( int n ){
int p = pcomp(n);
int p2 = p*p; // biggest power of two that is a square < n
int d = 1; // increase using odd numbers until n is exceeded
while( p2 + 2*p + d < n ){
p2 += 2*p + d;
d += 2;
}
return p2;
}
但我敢肯定,牛顿的算法更快.记住二次方收敛.
public static int sqrt( int n ){
int x = n;
while( true ){
int y = (x + n/x)/2;
if( y >= x ) return x;
x = y;
}
}
这将返回整数平方根.返回x * x以得到n之下的平方.