SGU111 Very simple problem

SGU111 Very simple problem

题目大意

输入一个大整数X,输出平方小于等于X的最大的整数

算法思路

二分答案,使用Java的BigInteger类可以避免手动实现高精度运算

时间复杂度: O(logX)

代码

/** * Copyright (c) 2015 Authors. All rights reserved. * * FileName: 111.java * Author: Beiyu Li <[email protected]> * Date: 2015-05-22 */
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

public class Solution {
    public static void main(String args[])
    {
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        BigInteger x = cin.nextBigInteger();
        BigInteger l = BigInteger.ONE, r = x;
        while (l.compareTo(r) < 0) {
            BigInteger mid = l.add(r).add(
                    BigInteger.ONE).divide(BigInteger.valueOf(2));
            if (mid.pow(2).compareTo(x) <= 0) l = mid;
            else r = mid.subtract(BigInteger.ONE);
        }
        System.out.println(l);
    }
}

你可能感兴趣的:(BIgInteger,sgu)