检测完全平方数的最短方法是什么?

31

@dogbane 那个问题已经因为重复而关闭了 :D - Dr. belisarius
4个回答

53

可能是在检查该数字的平方根是否有小数部分,或者它是否为整数。

在实现上,我会考虑像这样:

double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;

isSquare现在应该对所有的正方形返回true,对于其他所有图形返回false


10
我惊讶地发现百分号运算符也适用于双精度浮点数。 - Binary Worrier
14
以上答案并不总是对于大数正确。请尝试以下内容: double result = Math.Sqrt ( 3999680306388005621 ); bool isSquare = result % 1 == 0; long x = ( long ) result; long y = x * x; // y 不等于 3999680306388005621 - Setyo N
我不确定,但那可能是当数字开始失去精度/浮点数时发生的。 - Luke

7
这是一种检查平方根是否为整数的变体方法:
bool IsPerfectSquare(double input)
{
    var sqrt = Math.Sqrt(input);
    return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}

Math.Ceiling 方法会向上舍入为最接近的整数,而 Math.Floor 方法则向下舍入。如果两者相同,则结果为整数!

这也可以写成一行代码:

if (int(Math.Ceiling(Math.Sqrt(n))) == int(Math.Floor(Math.Sqrt(n)))) /* do something */;

2
Math.Ceiling()Math.Floor()返回一个双精度值,因此您可能会遇到问题。相反,进行浮点比较:if (Math.Abs(val1 - valu2) < Double.Epsilon) { ... } - michael
@michael,谢谢你,这是一个非常好的观点!我已经更新了我的答案来反映这一点! - Daren Thomas
有没有理由使用< Double.Epsilon而不是> 0 - j.i.h.

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接