Users Pricing

forum

home / developersection / forums / fastest way to determine if an integer's square root is an integer

Fastest way to determine if an integer's square root is an integer

Anonymous User 2285 13 May 2015
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). I've done it the easy way, by using the built-in Math.sqrt() function, but I'm wondering if there is a way to do it faster by restricting yourself to integer-only domain. Maintaining a lookup table is impratical (since there are about 231.5 integers whose square is less than 263).

Here is the very simple and straightforward way I'm doing it now:
public final static boolean isPerfectSquare(long n)
{
  if (n < 0)
    return false;
  long tst = (long)(Math.sqrt(n) + 0.5);
  return tst*tst == n;
}
Notes: I'm using this function in many Project Euler  problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.


I am a content writter !


1 Answers