Shortest way to check perfect Square? [duplicate]

拥有回忆 提交于 2019-12-03 08:22:19

问题


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, ......

回答1:


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.




回答2:


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 */;



回答3:


    public bool IsPerferctSquare(uint number)
    {
        return (Math.Sqrt(number) % 1 == 0);
    }



回答4:


public bool IsPerfectSquare(int num)
{
   int root = (int)Math.Sqrt(num);
   return (int) Math.Pow(root,2) == num;
}


来源:https://stackoverflow.com/questions/4885925/shortest-way-to-check-perfect-square

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!