java - BigInteger.pow(大整数)?

标签 java math biginteger pow

我正在玩 Java 中的数字,想看看我能做出多大的数字。我的理解是 BigInteger 可以容纳无限大小的数字,只要我的计算机有足够的内存来容纳这样的数字,对吗?

我的问题是 BigInteger.pow 只接受一个 int,而不接受另一个 BigInteger,这意味着我只能使用不超过 2,147,483,647 的数字作为指数。是否可以这样使用 BigInteger 类?

BigInteger.pow(BigInteger)

谢谢。

最佳答案

您可以自己编写,使用 repeated squaring :

BigInteger pow(BigInteger base, BigInteger exponent) {
  BigInteger result = BigInteger.ONE;
  while (exponent.signum() > 0) {
    if (exponent.testBit(0)) result = result.multiply(base);
    base = base.multiply(base);
    exponent = exponent.shiftRight(1);
  }
  return result;
}

可能不适用于负基数或指数。

关于java - BigInteger.pow(大整数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4582277/

相关文章:

algorithm - 是否有时间校正速度 Verlet 算法?

.net - 为什么 F# 中 bigint 缺少按位非运算符 (~~~)?

java - 错误: multiply(long) is not public in BigInteger; cannot be accessed from outside package

python - 一维数组形状 (length,) vs. (length,1) vs. (length)

小数点后 19 位及以上的数学精度

java - 模拟返回列表 future 的外部依赖

java - 不能用Eclipse做StringBuilder

java - 切换到 BigInteger 并且程序不再运行

java - Spring AOP @Before 服务中 - Before Advice 检查安全性

java - 如何从 java ArrayList 对象转换为实际值