0
点赞
收藏
分享

微信扫一扫

BigInteger开方

小布_cvg 2023-02-09 阅读 109


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;
}
}

 

举报

相关推荐

BigInteger

BigInteger用在循环

BigInteger与BigDecimal

Java BigInteger常见用法

BigInteger中的常用方法

0 条评论