java - 如何计算 2 的幂 N 其中 N 是一个非常大的数

标签 java biginteger pow

我需要找到 2 的 N 次方,其中 N 是一个非常大的数(Java BigInteger 类型)

Java BigInteger 类有 pow 方法,但它只接受整数值作为指数。

于是,我写了一个方法如下:

static BigInteger twoToThePower(BigInteger n)
   {
      BigInteger result = BigInteger.valueOf(1L);

      while (n.compareTo(BigInteger.valueOf((long) Integer.MAX_VALUE)) > 0)
      {
         result = result.shiftLeft(Integer.MAX_VALUE);
         n = n.subtract(BigInteger.valueOf((long) Integer.MAX_VALUE));

      }

      long k = n.longValue();
      result = result.shiftLeft((int) k);

      return result;
   }

我的代码运行良好,我只是分享我的想法,很想知道是否还有其他更好的想法?

谢谢。

最佳答案

您不能使用 BigInteger 来存储计算结果。来自 javadoc:

BigInteger must support values in the range -2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE (exclusive) and may support values outside of that range.

这就是 pow 方法采用 int 的原因。在我的机器上,BigInteger.ONE.shiftLeft(Integer.MAX_VALUE) 抛出 java.lang.ArithmeticException(消息是“BigInteger 会溢出支持的范围”)。

关于java - 如何计算 2 的幂 N 其中 N 是一个非常大的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687092/

相关文章:

java - Gradle : one jar per classes directory

java - android中20秒后终止无限循环

linux - 在两个不同的 Linux 操作系统上获得 pow() 函数的两个不同结果

特征值:向量或矩阵分量的幂?

c++ - 为什么标准 C++ 库中没有 `int pow(int base, int exponent)`?

java - IntelliJ IDEA 中的实时编译

java - 正则表达式中的问号 : difference between 'Pattern.compile("\"title\":\"(.*?)\"") ;' and ' Pattern. 编译 ("\"标题\":\".*\"");'

java - 转换具有非常大数字的十六进制值的字符串

Java 大整数 - 嵌套 get

c++ - 优化c++代码以添加两个作为字符串的数字