CSU 1211: 大整数开平方练习(二分)

CSU 1211: 大整数开平方练习 二分

Description

对大整数开平方,向下取整

Input

每行一个正整数,位数1 <= len <= 1000

Output

每行对应输出正整数的平方根。

Sample Input

37
12345678987654321

Sample Output

6
111111111

Hint

Source

CSGrandeur的数据结构习题

思路:二分,极限过

import java.util.*;
import java.math.*;
public class Main{
    public static void main(String args[]){
        BigInteger i;
        Scanner input = new Scanner(System.in);
        while(input.hasNext()){
            i = input.nextBigInteger();
            BigInteger l = BigInteger.ZERO;
            BigInteger r = i;
            BigInteger mid;
            while(r.subtract(l).compareTo(BigInteger.ZERO) > 0){
                mid = l.add(r.add(BigInteger.ONE)).divide(BigInteger.valueOf(2));
                if(judge(mid,i) == 1)
                    l = mid;
                else
                    r = mid.subtract(BigInteger.ONE);
            }
            System.out.println(l);
        }
    }
    public static int judge(BigInteger x,BigInteger i){
        if(x.multiply(x).compareTo(i) <= 0)
            return 1;
        else return 0;
    }
}

你可能感兴趣的:(高精度算法,二分,csuoj,acm,大整数开方)