Check if BigInteger is not a perfect square

后端 未结 6 1704
悲&欢浪女
悲&欢浪女 2020-12-29 14:12

I have a BigInteger value, let\'s say it is 282 and is inside the variable x. I now want to write a while loop that states:

while b2 isn\'t a perfect square:         


        
6条回答
  •  清酒与你
    2020-12-29 14:56

    Compute the integer square root, then check that its square is your number. Here is my method of computing the square root using Heron's method:

    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;
    }
    

提交回复
热议问题