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