I\'m looking for the fastest way to determine if a long
value is a perfect square (i.e. its square root is another integer):
If you wish to avoid non-integer operations you could use the method below. It basically uses Newton's Method modified for integer arithmetic.
/**
* Test if the given number is a perfect square.
* @param n Must be greater than 0 and less
* than Long.MAX_VALUE.
* @return true
if n is a perfect
* square, or false
otherwise.
*/
public static boolean isSquare(long n)
{
long x1 = n;
long x2 = 1L;
while (x1 > x2)
{
x1 = (x1 + x2) / 2L;
x2 = n / x1;
}
return x1 == x2 && n % x1 == 0L;
}
This implementation can not compete with solutions that use Math.sqrt
. However, its performance can be improved by using the filtering mechanisms described in some of the other posts.