Java 高精度开根!(BZOJ 1213)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mrx_Nh/article/details/75286884

给定 m,n (1m50,0n1010000)  nm   的整数部分.
因为只要求整数部分,所以不必用 BigDecimal 类去二分,那样反而会浪费时间,最后判断边界值即可.
构造至 :  lmn<rm, r=2l , 然后在 [l,r] 二分找答案即可.

import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static void  main(String args[]){
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        BigInteger n;
        int m;
        while(cin.hasNext()) {
          m = cin.nextInt();
          n = cin.nextBigInteger();
          BigInteger l = BigInteger.ZERO;
          BigInteger r = BigInteger.ONE;
          while(r.pow(m).compareTo(n) != 1) {      // r^m <= n
              l = r;
              r = r.multiply(BigInteger.valueOf(2));
          }
          while(l.add(BigInteger.valueOf(1)).compareTo(r) == -1) {   // l + 1 <= r
              BigInteger mid = (l.add(r)).divide(BigInteger.valueOf(2));
              if(mid.pow(m).compareTo(n) != 1) {   // mid ^ m <= n
                  l = mid;
              } else {
                  r = mid;
              }
          }
          BigInteger ans;
          if(r.pow(m).compareTo(n) != 1) {
              ans = r;
          } else {
              ans = l;
          }
          System.out.println(ans);
        }
    }
}
阅读更多
换一批

没有更多推荐了,返回首页