我正在玩 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/