检查BigInteger是不是一个完美的正方形

Mik*_*e B 8 java math biginteger

我有一个BigInteger值,假设它是282并且在变量x内.我现在想写一个while循环,声明:

while b2 isn't a perfect square:
    a ? a + 1
    b2 ? a*a - N
endwhile
Run Code Online (Sandbox Code Playgroud)

我如何使用BigInteger做这样的事情?

编辑:这样做的目的是我可以写这个方法.正如文章所述,必须检查b2是否不是正方形.

sta*_*lue 11

计算整数平方根,然后检查其平方是否为数字.这是我使用Heron方法计算平方根的方法:

private static final BigInteger TWO = BigInteger.valueOf(2);


/**
 * Computes the integer square root of a number.
 *
 * @param n  The number.
 *
 * @return  The integer square root, i.e. the largest number whose square
 *     doesn't exceed n.
 */
public static BigInteger sqrt(BigInteger n)
{
    if (n.signum() >= 0)
    {
        final int bitLength = n.bitLength();
        BigInteger root = BigInteger.ONE.shiftLeft(bitLength / 2);

        while (!isSqrt(n, root))
        {
            root = root.add(n.divide(root)).divide(TWO);
        }
        return root;
    }
    else
    {
        throw new ArithmeticException("square root of negative number");
    }
}


private static boolean isSqrt(BigInteger n, BigInteger root)
{
    final BigInteger lowerBound = root.pow(2);
    final BigInteger upperBound = root.add(BigInteger.ONE).pow(2);
    return lowerBound.compareTo(n) <= 0
        && n.compareTo(upperBound) < 0;
}
Run Code Online (Sandbox Code Playgroud)