BigInteger.pow(BigInteger的)?

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

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

BigInteger.pow(BigInteger) 

谢谢。

您可以使用重复的平方来编写自己的:

 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中执行此操作,这意味着您可以执行a ^ b mod c ,其中a,b,cBigInteger数字。

这是使用:

  BigInteger modPow(BigInteger exponent, BigInteger m) 

在这里阅读BigInteger.modPow文档。

BigInteger的底层实现仅限于(2 ^ 31-1)* 32位值。 这几乎是2 ^ 36位。 您将需要8 GB的内存来存储它,并且需要多次才能对其执行任何操作,如toString()。

顺便说一句:你永远无法读懂这样的数字。 如果您试图将其打印出来,则需要一生的时间来阅读它。

2 ^ 2,147,483,647至少有5亿个数字,实际上计算功率是NPC问题,[Pow是NPC的输入长度,2个输入(m,n)它们可以用O(logm + logn)编码并且可以占用nlog(m)(最后答案占用n log(m)空间)这不是输入和计算大小之间的多项式关系],有一些简单的问题实际上并不容易,例如sqrt(2)是某种它们,你不能指定真正的精度(所有精度),即BigDecimal说可以计算所有精度,但它不能(实际上),因为到目前为止还没有人解决这个问题。

java不会让你做BigInteger.Pow(BigInteger),但你可以把它放到循环中的最大整数,看看抛出ArithmeticException的地方或由于内存不足导致的其他错误。

我建议你使用BigInteger modPow(BigInteger exponent,BigInteger m)

假设您有BigInteger X和BigInteger Y,并且您想要计算BigInteger Z = X ^ Y.

得到一个大的素数P >>>> X ^ Y并做Z = X.modPow(Y,P);

对于任何从Groovy方面发现这一点的人来说,完全有可能将BigInteger传递给BigInteger.pow()。

 groovy> def a = 3G.pow(10G) groovy> println a groovy> println a.class 59049 class java.math.BigInteger 

http://docs.groovy-lang.org/2.4.3/html/groovy-jdk/java/math/BigInteger.html#power%28java.math.BigInteger%29

只需使用.intValue()如果您的BigInteger名为BigValue2,那么它将是BigValue2.intValue()

所以回答你的问题,就是这样

 BigValue1.pow(BigValue2.intValue())