bool IsPerfectSquare(long input)
{
long closestRoot = (long) Math.Sqrt(input);
return input == closestRoot * closestRoot;
}
Это может убежать [приблизительно 112] из проблем просто проверки, "квадратный корень целое число", но возможно не все. Потенциально необходимо стать немного более напуганными:
bool IsPerfectSquare(long input)
{
double root = Math.Sqrt(input);
long rootBits = BitConverter.DoubleToInt64Bits(root);
long lowerBound = (long) BitConverter.Int64BitsToDouble(rootBits-1);
long upperBound = (long) BitConverter.Int64BitsToDouble(rootBits+1);
for (long candidate = lowerBound; candidate <= upperBound; candidate++)
{
if (candidate * candidate == input)
{
return true;
}
}
return false;
}
Неприглядный, и ненужный для чего-либо кроме действительно больших значений, но я думаю, что это должно работа...
bool IsPerfectSquare(long input)
{
long SquareRoot = (long) Math.Sqrt(input);
return ((SquareRoot * SquareRoot) == input);
}
В языке Common LISP я использую следующее:
(defun perfect-square-p (n)
(= (expt (isqrt n) 2)
n))