is BigInteger Perfect Square - Java java.math

Java examples for java.math:BigInteger

Description

is BigInteger Perfect Square

Demo Code


import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Arraycopy;
import java.util.Random;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

public class Main{
    public static void main(String[] argv) throws Exception{
        BigInteger n = new BigInteger("1234");
        System.out.println(isPerfectSquare(n));
    }/*from  w  w w  .java2s  .  c om*/
    public static final BigInteger MAXINT = BigInteger
            .valueOf(Integer.MAX_VALUE);
    public static final BigInteger ITERBETTER = ONE.shiftLeft(1024);
    public static boolean isPerfectSquare(BigInteger n) {
        return fullSqrt(n)[1].signum() == 0;
    }
    public static BigInteger[] fullSqrt(BigInteger n) {

        if (n.compareTo(MAXINT) < 1) {
            long ln = n.longValue();
            long s = (long) java.lang.Math.sqrt(ln);

            return new BigInteger[] { BigInteger.valueOf(s),
                    BigInteger.valueOf(ln - s * s) };
        }

        BigInteger[] sr = isqrtInternal(n, n.bitLength() - 1);
        if (sr[1].signum() < 0) {
            return new BigInteger[] { sr[0].subtract(ONE),
                    sr[1].add(sr[0].shiftLeft(1)).subtract(ONE) };
        }
        return sr;
    }
    public static BigInteger sqrt(BigInteger n) {
        return fullSqrt(n)[0];
    }
    private static BigInteger[] isqrtInternal(BigInteger n, int log2n) {
        if (n.compareTo(MAXINT) < 1) {
            int ln = n.intValue(), s = (int) java.lang.Math.sqrt(ln);
            return new BigInteger[] { BigInteger.valueOf(s),
                    BigInteger.valueOf(ln - s * s) };
        }
        if (n.compareTo(ITERBETTER) < 1) {
            int d = 7 * (log2n / 14 - 1), q = 7;
            BigInteger s = BigInteger.valueOf((long) java.lang.Math.sqrt(n
                    .shiftRight(d << 1).intValue()));
            while (d > 0) {
                if (q > d)
                    q = d;
                s = s.shiftLeft(q);
                d -= q;
                q <<= 1;
                s = s.add(n.shiftRight(d << 1).divide(s)).shiftRight(1);
            }
            return new BigInteger[] { s, n.subtract(s.multiply(s)) };
        }
        int log2b = log2n >> 2;
        BigInteger mask = ONE.shiftLeft(log2b).subtract(ONE);
        BigInteger[] sr = isqrtInternal(n.shiftRight(log2b << 1), log2n
                - (log2b << 1));
        BigInteger s = sr[0];
        BigInteger[] qu = sr[1].shiftLeft(log2b)
                .add(n.shiftRight(log2b).and(mask))
                .divideAndRemainder(s.shiftLeft(1));
        BigInteger q = qu[0];
        return new BigInteger[] {
                s.shiftLeft(log2b).add(q),
                qu[1].shiftLeft(log2b).add(n.and(mask))
                        .subtract(q.multiply(q)) };
    }
}

Related Tutorials