我试图在 Java 中找到判断一个整数是否有完美平方根的最高效方案?如果一个整数的平方根也是一个整数,那么这个整数就有完美平方根。
下面是我想到的一个最简单的方法,其中调用了 Math.sqrt() 方法,这有可能影响性能:
public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
long tst = (long)(Math.sqrt(n) + 0.5);
return tst*tst == n;
}
回答
要验证算法是否最优,最好需要做一些基准测试。
你的算法看起来很不错,不过还有优化的空间,可以在调用 Math.sqrt() 方法之前排除一些可能性。比如,通过观察,有完美平方根的整数,它的十六进制形式的结尾只能是 0、1、4 或 9。这样就能通过判断过滤了 75% 的数字。
下面的代码演示了如何利用这种判断,当数字是 1 到 100000000 之间时,这段代码的运行速度是原来的两倍:
public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
switch((int)(n & 0xF))
{
case 0: case 1: case 4: case 9:
long tst = (long)Math.sqrt(n);
return tst*tst == n;
default:
return false;
}
}
我在 C++ 中做了类似的测试,但是速度比原始版本还慢,怀疑是 switch 语句导致了速度变慢,取消 switch 语句后,运行速度提高到原始版本的两倍。在 C# 中做测试,使用 switch 没有问题,速度是原始版本的两倍。
下面是在 Java 中不使用 switch 语句的版本:
int isPerfectSquare(int n)
{
int h = n & 0xF; // h is the last hex "digit"
if (h > 9)
return 0;
// Use lazy evaluation to jump out of the if statement as soon as possible
if (h != 2 && h != 3 && h != 5 && h != 6 && h != 7 && h != 8)
{
int t = (int) floor( sqrt((double) n) + 0.5 );
return t*t == n;
}
return 0;
}
当然,这并不是最优解,还有提升的空间。结合上面的思想,再开发一个更优的方案:
private final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
switch((int)(n & 0x3F))
{
case 0x00: case 0x01: case 0x04: case 0x09: case 0x10: case 0x11:
case 0x19: case 0x21: case 0x24: case 0x29: case 0x31: case 0x39:
long sqrt;
if(n < 410881L)
{
//John Carmack hack, converted to Java.
// See: http://www.codemaestro.com/reviews/9
int i;
float x2, y;
x2 = n * 0.5F;
y = n;
i = Float.floatToRawIntBits(y);
i = 0x5f3759df - ( i >> 1 );
y = Float.intBitsToFloat(i);
y = y * ( 1.5F - ( x2 * y * y ) );
sqrt = (long)(1.0F/y);
}
else
{
//Carmack hack gives incorrect answer for n >= 410881.
sqrt = (long)Math.sqrt(n);
}
return sqrt*sqrt == n;
default:
return false;
}
}