パーフェクトスクエアをチェックする最短の方法は? [複製
-
28-10-2019 - |
質問
数字を確認するための最短で最も簡単な方法が必要です。
完璧な正方形のいくつか:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
解決
おそらく、数字の平方根に小数部があるかどうか、またはそれが整数であるかどうかを確認します。
実装ごとに、私は次のようなことを考えます:
double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;
isSquare
今はそうあるべきです true
すべての正方形のために、そして false
他のすべてのために。
他のヒント
これは、平方根が積分であるかどうかを確認する際のバリアントです。
bool IsPerfectSquare(double input)
{
var sqrt = Math.Sqrt(input);
return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}
Math.Ceiling
次の整数にまとめますが、 Math.Floor
倒れます。彼らが同じなら、まあ、あなたは整数を持っています!
これは、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);
}
public bool IsPerfectSquare(int num)
{
int root = (int)Math.Sqrt(num);
return (int) Math.Pow(root,2) == num;
}
所属していません StackOverflow