Shortest way to check perfect Square? [duplicate]
-
28-10-2019 - |
Question
Possible Duplicate:
What's a good algorithm to determine if an input is a perfect square?
I want Shortest and Simplest way to Check a number is perfect square in C#
Some of Perfect Squares:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
Solution
Probably checking if the square root of the number has any decimal part, or if it is a whole number.
Implementationwise, I would consider something like this:
double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;
isSquare
should now be true
for all squares, and false
for all others.
OTHER TIPS
This is a variant on checking if the square root is integral:
bool IsPerfectSquare(double input)
{
var sqrt = Math.Sqrt(input);
return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}
Math.Ceiling
will round up to the next integer, whereas Math.Floor
will round down. If they are the same, well, then you have an integer!
This can also be written as a oneliner:
if (int(Math.Ceiling(Math.Sqrt(n))) == int(Math.Floor(Math.Sqrt(n)))) /* do something */;
public bool IsPerferctSquare(uint number)
{
return (Math.Sqrt(number) % 1 == 0);
}
public bool IsPerfectSquare(int num)
{
int root = (int)Math.Sqrt(num);
return (int) Math.Pow(root,2) == num;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow