BigInteger开方

阅读 109

2023-02-09


import java.math.BigInteger;
import java.util.Scanner;

public class 大数开方2 {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

for (int i = 0; i < 20; i++) {
BigInteger n=BigInteger.valueOf(i);
System.out.println(sqrt(n));

}


}

private static BigInteger sqrt(BigInteger n) {
BigInteger a;
BigInteger b;

//a为10的,n的长度除以二的,十次方
a=BigInteger.TEN.pow((int)n.toString().length()/2);
//b=n/a
b=n.divide(a);

//如果,a!=b,或者a和b的差相差不为0
while(!(a.equals(b)||a.equals(b.add(new BigInteger("-1")))||b.equals(a.add(new BigInteger("-1"))))){

//a=(a+b)/2
a=a.add(b).divide(new BigInteger("2"));
//b=n/a;
b=n.divide(a);
}
//取a,b中较小的一个
if (a.equals(b.add(new BigInteger("-1")))) {
return a;
}

return b;
}
}

 

精彩评论(0)

0 0 举报