C#で数値が完全平方であることを確認する最短かつ簡単な方法が欲しい
完全な正方形の一部:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
C#で数値が完全平方であることを確認する最短かつ簡単な方法が欲しい
完全な正方形の一部:
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
切り上げますが、切り捨てます。それらが同じであれば、まあ、あなたは整数を持っています!
これはワンライナーとして書くこともできます:
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;
}