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 (...
Closed as Exact Duplicate:
Fastest way to determine if an integer’s square root is an integer
What's a way to see if a number is a perfect square?
bool IsPerfectSquare(long input)
{
// TODO
}
I'm using C# but this is language agnostic.
Bonus points for clarity and simplicity (this isn't meant to be code-golf).
Edit: T...
Can I rely on
sqrt((float)a)*sqrt((float)a)==a
or
(int)sqrt((float)a)*(int)sqrt((float)a)==a
to check whether a number is a perfect square? Why or why not?
int a is the number to be judged. I'm using Visual Studio 2005.
Edit: Thanks for all these rapid answers. I see that I can't rely on float type comparison. (If I wrote as a...