Shortest way to check perfect Square? [duplicate]

只谈情不闲聊 提交于 2019-12-02 22:08:41

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);
    }
Itay Karo
public bool IsPerfectSquare(int num)
{
   int root = (int)Math.Sqrt(num);
   return (int) Math.Pow(root,2) == num;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!