// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.math.BigInteger;
import java.util.Random;

public class BigSqrt {
    private static Random rng = new Random();
    public static void main(String[] args) {
        BigInteger twelve = new BigInteger("12");
        System.out.println(sqrt(twelve));
        for(int i = 0; i < 100; i++) {
            byte[] b = new byte[1];
            b[0] = (byte)i;
            BigInteger x = new BigInteger(b);
            System.out.println(i + " " + (int)Math.sqrt(i) + " " + sqrt(x));
        }
        byte[] b = new byte[3000];
        rng.nextBytes(b);
        if(b[0] < 0) {
            b[0] = (byte)(b[0] & 0x7F);
        }
        BigInteger x = new BigInteger(b);
        System.out.println(x);
        long t3 = System.currentTimeMillis();
        BigInteger xsqrt2 = sqrt(x);
        long t4 = System.currentTimeMillis();
        System.out.println(xsqrt2);
        System.out.println(t4 - t3);
    }
    private final static BigInteger one = new BigInteger("1");
    private final static BigInteger two = new BigInteger("2");
    public static BigInteger sqrt(BigInteger v) {
        int n = v.toByteArray().length;
        byte[] b = new byte[n/2+1];
        b[0] = 1;
        BigInteger guess = new BigInteger(b);
        while(true) {
            BigInteger guessadd1 = guess.add(one);
            BigInteger guesssub1 = guess.subtract(one);
            if(guess.multiply(guess).compareTo(v) > 0) {
                if(guesssub1.multiply(guesssub1).compareTo(v) <= 0) {
                    return guesssub1;
                }
            } else {
                if(guessadd1.multiply(guessadd1).compareTo(v) > 0) {
                    return guess;
                }
            }
            guess = guess.add(v.divide(guess)).divide(two);
        }
    }
}
