1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| 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; } }
|