Shortest way to check perfect Square?
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, ......
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.
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);
}
链接地址: http://www.djcxy.com/p/86608.html
上一篇: jol GraphLayout输出中的“(其他)”是什么?
下一篇: 最简单的方法来检查完美的广场?