BigInteger.pow(BigInteger)?

2019-01-12 02:34发布

I'm playing with numbers in Java, and want to see how big a number I can make. It is my understanding that BigInteger can hold a number of infinite size, so long as my computer has enough Memory to hold such a number, correct?

My problem is that BigInteger.pow accepts only an int, not another BigInteger, which means I can only use a number up to 2,147,483,647 as the exponent. Is it possible to use the BigInteger class as such?

BigInteger.pow(BigInteger)

Thanks.

8条回答
Viruses.
2楼-- · 2019-01-12 02:52

For anyone who stumbles upon this from the Groovy side of things, it is totally possible to pass a BigInteger to 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

查看更多
放我归山
3楼-- · 2019-01-12 02:57

java wont let you do BigInteger.Pow(BigInteger) but you can just put it to the max integer in a loop and see where a ArithmeticException is thrown or some other error due to running out of memory.

查看更多
Bombasti
4楼-- · 2019-01-12 03:02

You can only do this in Java by modular arithmetic, meaning you can do a a^b mod c, where a,b,c are BigInteger numbers.

This is done using:

 BigInteger modPow(BigInteger exponent, BigInteger m) 

Read the BigInteger.modPow documentation here.

查看更多
男人必须洒脱
5楼-- · 2019-01-12 03:02

I can suggest you make use of BigInteger modPow(BigInteger exponent, BigInteger m)

Suppose you have BigInteger X, and BigInteger Y and you want to calculate BigInteger Z = X^Y.

Get a large Prime P >>>> X^Y and do Z = X.modPow(Y,P);

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-12 03:07

You can write your own, using 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;
}

might not work for negative bases or exponents.

查看更多
趁早两清
7楼-- · 2019-01-12 03:11

The underlying implementation of BigInteger is limited to (2^31-1) * 32-bit values. which is almost 2^36 bits. You will need 8 GB of memory to store it and many times this to perform any operation on it like toString().

BTW: You will never be able to read such a number. If you tried to print it out it would take a life time to read it.

查看更多
登录 后发表回答