如何在java中找到像2 ^(10 ^ 9)这样的数的幂次幂

Math.pow()返回一个double值,只接受int作为参数… BigInteger没有找到BigInteger的函数^ BigInteger通过循环执行它需要很长时间…我还有什么方法可以丢失吗?

Thnx提前……

您可以使用BigInteger.pow()来获取大指数。 由于10 9适合int并且也可以完全表示为double ,因此您可以这样做:

 int exp = (int) Math.pow(10, 9); BigInteger answer = BigInteger.valueOf(2).pow(exp); 

对于大于Integer.MAX_VALUE指数,这显然会中断。 但是,您可以使用BigInteger.modPow(BigInteger exponent, BigInteger m)BigInteger作为电源,另一个BigInteger作为第三个BigInteger引发。 您只需要首先创建一个比预期答案大的BigInteger作为模数。

如果你有2 ^ x,其中x是一个大数字,那么你可以通过位移来实现。 例:

 2^4 == (1 << 4); 2^12 == (1 << 12); 

使用BigIntegers,您可以使用shiftLeft()和shiftRight()方法执行相同的操作。

Math.pow()返回一个double值,只接受int作为参数。

不,它需要两个双打并返回一个双: Javadoc 。

如果你不需要确切的答案,它可能会做得很好。

你可以使用战俘,但左移可能会更快。

  BigInteger bi = BigInteger.ONE.shiftLeft(1_000_000_000); 

BigInteger.pow(BigInteger)不支持的原因很可能是即使是最琐碎的例子,你需要比世界上任何计算机都要多的内存来保存这样的值。 需要BigInteger指数的最小值是2 ^ 63和2 << 2 ^ 63需要2 ^ 60字节的内存或1万亿GB。