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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19734408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:48:39  来源:igfitidea点击:

How to find power of power of a number like 2^(10^9) in java

java

提问by gonephishing

Math.pow() returns a double value and takes only int as parameters...BigInteger as no function for finding BigInteger^BigInteger Doing it through loops takes really long time... Is there any more way i am missing?

Math.pow() 返回一个 double 值并且只接受 int 作为参数...BigInteger 作为没有函数来查找 BigInteger^BigInteger 通过循环来做它需要很长时间......还有我缺少的其他方法吗?

Thnx in advance...

提前谢谢...

采纳答案by Ted Hopp

You can use BigInteger.pow()to take a large exponent. Since 109fits into an intand is also exactly representable as a double, you can do this:

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

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

This obviously breaks down for exponents larger than Integer.MAX_VALUE. However, you can then use BigInteger.modPow(BigInteger exponent, BigInteger m)to raise a BigIntegerto another BigIntegeras a power, module a third BigInteger. You just need to first create a BigIntegerthat is larger than your expected answer to serve as a modulus.

对于大于 的指数,这显然会失效Integer.MAX_VALUE。但是,您可以使用BigInteger.modPow(BigInteger exponent, BigInteger m)将 a 提升BigInteger到另一个BigInteger作为幂,模块 a 的第三个BigInteger。您只需要首先创建一个BigInteger比您预期的答案大的作为模数。

回答by NPE

Math.pow()returns a double value and takes only int as parameters.

Math.pow()返回一个双精度值并且只接受 int 作为参数。

No, it takes two doubles and returns a double: Javadoc.

不,它需要两个双精度值并返回一个双精度值:Javadoc

If you don't need the exact answer, it will probably do just fine.

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

回答by Dale Myers

If you have 2^x, where x is some large number then you can do this through bit shifting. Example:

如果你有 2^x,其中 x 是一些大数,那么你可以通过位移来做到这一点。例子:

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

With BigIntegers you can do the same thing with the shiftLeft() and shiftRight() methods.

使用 BigIntegers,您可以使用 shiftLeft() 和 shiftRight() 方法做同样的事情。

回答by Peter Lawrey

You can use pow, but left shift is likely to be faster.

您可以使用 pow,但左移可能会更快。

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

The reason BigInteger.pow(BigInteger) is not support is likely to be that for even the most trivial examples, you would need more memory than any computer in the world to hold such a value. The smallest value which requires a BigInteger exponent is 2^63 and 2<<2^63 requires 2^60 bytes of memory or one trillion GB.

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