sqrt BigInteger - Java java.math

Java examples for java.math:BigInteger

Description

sqrt BigInteger

Demo Code


//package com.java2s;
import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) throws Exception {
        BigInteger x = new BigInteger("1234");
        System.out.println(sqrt(x));
    }//  w  ww .  j  av  a 2  s  .  c o  m

    public static BigInteger sqrt(BigInteger x) {
        BigInteger div = BigInteger.ZERO.setBit(x.bitLength() / 2);
        BigInteger div2 = div;
        // Loop until we hit the same value twice in a row, or wind
        // up alternating.
        for (;;) {
            BigInteger y = div.add(x.divide(div)).shiftRight(1);
            if (y.equals(div) || y.equals(div2))
                return y;
            div2 = div;
            div = y;
        }
    }
}

Related Tutorials