In this example we will show how to find square root of BigInteger with NEWTON’s method.
Source Code
package com.beginner.examples;
import java.math.BigInteger;
public class FindSquareRootBigIntegerExample {
public static void main(String[] args) {
// 2 to the 1000
BigInteger bigInteger = new BigInteger("2").pow(100);
// Get its string
String strBigNum = bigInteger.toString();
if (strBigNum.length() % 2 == 1) {
strBigNum = "0" + strBigNum;
}
// Store the remainder
String remainder = "0";
// Store the result
String squareRootResult = "0";
for (int i = 0; i < strBigNum.length() / 2; i++) {
// The remainder plus the truncated two-digit number
String remainder2 = remainder
+ strBigNum.substring(i * 2, i * 2 + 2);
BigInteger resultBigInteger = new BigInteger(squareRootResult);
BigInteger remainderBigInteger = new BigInteger(remainder2);
for (int j = 0; j <= 9; j++) {
String num1 = "" + j;
String num2 = "" + (j + 1);
BigInteger testN1 = new BigInteger(num1);
BigInteger testN2 = new BigInteger(num2);
//Try,
BigInteger n1_ = resultBigInteger
.multiply(new BigInteger("20")).add(testN1);
BigInteger n2_ = resultBigInteger
.multiply(new BigInteger("20")).add(testN2);
if (n1_.multiply(testN1).compareTo(remainderBigInteger) 0) {
squareRootResult += j;
remainder = remainderBigInteger.subtract(
(n1_.multiply(testN1))).toString();
break;
}
}
}
System.out.println(squareRootResult.substring(1));
}
}
Output:
1125899906842624
References
Imported packages in Java documentation: