java判断求三次开方_在 Java 中如何判断一个整数有完美平方根?

我试图在 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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值