Check if BigInteger is not a perfect square

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

    I use this:

    SQRPerfect is the number I want to test: This also has a nice Square Root so you get to use this as well if you need it seperately. You can get a little speed up if you bring the Square Root inside the Perfect Square test, but I like having both functions.

    if(PerfectSQR(SQRPerfect)){
        Do Something
    }
    
    
    public static Boolean PerfectSQR(BigInteger A) {
        Boolean p=false;
        BigInteger B=SQRT(A);
        BigInteger C=B.multiply(B);
        if (C.equals(A)){p=true;}
        return p;
    }
    
    public static BigInteger SQRT(BigInteger A) {
        BigInteger a=BigInteger.ONE,b=A.shiftRight(5).add(BigInteger.valueOf(8));
        while ((b.compareTo(a))>=0){
            BigInteger mid = a.add(b).shiftRight(1);
            if (mid.multiply(mid).compareTo(A)>0){b=mid.subtract(BigInteger.ONE);}
            else{a=mid.add(BigInteger.ONE);}
        }
      return a.subtract(BigInteger.ONE);
    }
    

提交回复
热议问题