检查完美广场的最短路径?

Jav*_*ram 25 c# square-root

可能重复:
确定输入是否是完美正方形的好算法是什么?

我希望用最短最简单的方法来检查数字是否是C#中的完美平方

一些完美的正方形:

1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
Run Code Online (Sandbox Code Playgroud)

Øyv*_*hen 40

可能检查数字的平方根是否有任何小数部分,或者它是否是整数.

在实现方面,我会考虑这样的事情:

double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;
Run Code Online (Sandbox Code Playgroud)

isSquare现在应该true适用于所有广场,以及false所有其他广场.

  • 上面的答案并不总是正确的大数字.试试这个:double result = Math.Sqrt(3999680306388005621); bool isSquare =结果%1 == 0; long x =(长)结果; long y = x*x; // y不是3999680306388005621 (11认同)
  • +1:我很惊讶%运算符处理双精度数 (9认同)

Dar*_*mas 5

这是检查平方根是否为整数的变体:

bool IsPerfectSquare(double input)
{
    var sqrt = Math.Sqrt(input);
    return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}
Run Code Online (Sandbox Code Playgroud)

Math.Ceiling将向上舍入到下一个整数,而Math.Floor将向下舍入.如果它们是相同的,那么你有一个整数!

这也可以写成oneliner:

if (int(Math.Ceiling(Math.Sqrt(n))) == int(Math.Floor(Math.Sqrt(n)))) /* do something */;
Run Code Online (Sandbox Code Playgroud)

  • `Math.Ceiling()`和`Math.Floor()`返回一个double值,所以你在这里遇到可能的问题.相反,做一个浮点比较:`if(Math.Abs​​(val1 - valu2)<Double.Epsilon){...}` (2认同)

raj*_*esh 5

    public bool IsPerferctSquare(uint number)
    {
        return (Math.Sqrt(number) % 1 == 0);
    }
Run Code Online (Sandbox Code Playgroud)