square root Big Int - Android java.lang

Android examples for java.lang:Math

Description

square root Big Int

Demo Code


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

public class Main {
    public static BigInteger sqrtBigInt(BigInteger i) {
        long c;// www  .  j a  v  a  2  s  .  c o  m
        BigInteger medium;
        BigInteger high = new BigInteger(i.toString());
        BigInteger low = BigInteger.ONE;
        while (high.subtract(low).compareTo(BigInteger.ONE) > 0) {
            medium = high.add(low).divide(
                    BigInteger.ONE.add(BigInteger.ONE));
            c = medium.multiply(medium).compareTo(i);
            if (c > 0)
                high = medium;
            if (c < 0)
                low = medium;
            if (c == 0)
                return medium;
        }
        if (high.multiply(high).compareTo(i) == 0)
            return high;
        else
            return low;
    }
}

Related Tutorials