Find Square Root of BigInteger - Java Language Basics

Java examples for Language Basics:BigInteger

Description

Find Square Root of BigInteger

Demo Code


import java.math.BigDecimal;
import java.math.BigInteger;

public class Main {
  public static void main(String[] args) {
    String n = "";

    BigInteger my2P100000 = new BigInteger("0");
    BigInteger two = new BigInteger("2");

    my2P100000 = two.shiftLeft(2000 - 1);

    System.out.println("Value of 2^2,000 " + my2P100000);
    System.out.println("Finding the Square Root of 2^2000");

    String mys = my2P100000 + "";
    n = (mys);//from  www. j  a  v  a2 s  .c om
    int firsttime = 0;

    BigDecimal myNumber = new BigDecimal(n);
    BigDecimal g = new BigDecimal("1");
    BigDecimal my2 = new BigDecimal("2");
    BigDecimal epsilon = new BigDecimal("0.0000000001");

    BigDecimal nByg = myNumber.divide(g, 9, BigDecimal.ROUND_FLOOR);

    BigDecimal nBygPlusg = nByg.add(g);

    BigDecimal nBygPlusgHalf = nBygPlusg.divide(my2, 9, BigDecimal.ROUND_FLOOR);

    BigDecimal saveg = nBygPlusgHalf;
    firsttime = 99;

    do {
      g = nBygPlusgHalf;
      nByg = myNumber.divide(g, 9, BigDecimal.ROUND_FLOOR);
      nBygPlusg = nByg.add(g);
      nBygPlusgHalf = nBygPlusg.divide(my2, 9, BigDecimal.ROUND_FLOOR);
      BigDecimal savegdiff = saveg.subtract(nBygPlusgHalf);

      if (savegdiff.compareTo(epsilon) == -1) {
        firsttime = 0;
      } else {
        saveg = nBygPlusgHalf;
      }

    } while (firsttime > 1);

    System.out.println("For " + mys + "\nLength: " + mys.length() + "\nThe Square Root is " + saveg);
  }
}

Result


Related Tutorials