我需要找到 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/