Check if BigInteger is not a perfect square

后端 未结 6 1660
悲&欢浪女
悲&欢浪女 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:57

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

    I tried the above using JavaScript BigInt:

    function isPerfectSqrt(n, root) {
      const lowerBound = root**2n;
      const upperBound = (root+1n)**2n
      return lowerBound <= n && n < upperBound;
    }
    

    And found it was only about 60% as fast (in Node V8) as the one-liner:

    function isPerfectSqrt(n, root) {
      return (n/root === root && n%root === 0n)
    }
    

提交回复
热议问题