1213: [HNOI2004]高精度开根
Time Limit: 50 Sec Memory Limit: 162 MB
Submit: 2512 Solved: 851
Description
晓华所在的工作组正在编写一套高精度科学计算的软件,一些简单的部分如高精度加减法、乘除法早已写完了,现在就剩下晓华所负责的部分:实数的高精度开m次根。因为一个有理数开根之后可能得到一个无理数,所以这项工作是有较大难度的。现在要做的只是这项工作的第一步:只对自然数进行开整数次根,求出它的一个非负根,并且不考虑结果的小数部分,只要求把结果截断取整即可。程序需要根据给定的输入,包括需要开根的次数,以及被开根的整数;计算出它的非负根取整后的结果。
Input
共有两行,每行都有一个整数,并且输入中没有多余的空格:第一行有一个正整数m (1 <= m <= 50),表示要开的根次;第二行有一个整数n (0<=n <= 10^10000),表示被开根的数。
Output
只有一行,包括一个数,即为开根取整后的结果。
Sample Input
3
1000000000
Sample Output
1000
链接:
https://www.lydsy.com/JudgeOnline/problem.php?id=1213
思路:
BigInteger二分
l m < = n < = r m l^m<= n <=r^m lm<=n<=rm, r = 2 ∗ l r=2*l r=2∗l。来二分查找
代码:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
static BigInteger f(BigInteger x, BigInteger m)
{
BigInteger ans = BigInteger.ONE;
BigInteger a = BigInteger.ONE;
for(BigInteger i = BigInteger.ZERO; i.compareTo(m) < 0; i=i.add(a)) {
ans = ans.multiply(x);
}
return ans;
}
static BigInteger solve(BigInteger n, BigInteger m)
{
BigInteger l = BigInteger.ZERO;
BigInteger a = BigInteger.ONE;
BigInteger b = BigInteger.valueOf(2);
BigInteger r = BigInteger.ONE;
BigInteger mid;
while(f(r,m).compareTo(n) <= 0) {
l = r;
r = r.multiply(b);
}
while(l.compareTo(r) <= 0) {
BigInteger s = l.add(r);
mid = s.divide(b);
if(f(mid,m).compareTo(n) <= 0) {
l = mid.add(a);
}
else {
r = mid.subtract(a);
}
}
return r;
}
public static void main(String[] args) {
Scanner cinn = new Scanner(System.in);
BigInteger n, m;
m = cinn.nextBigInteger();
n = cinn.nextBigInteger();
BigInteger res = solve(n, m);
System.out.println(res.toString());
}
}