Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

Thnx in advance...

like image 896
gonephishing Avatar asked Dec 16 '22 04:12

gonephishing


2 Answers

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

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 BigInteger to another BigInteger as a power, module a third BigInteger. You just need to first create a BigInteger that is larger than your expected answer to serve as a modulus.

like image 88
Ted Hopp Avatar answered May 14 '23 19:05

Ted Hopp


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

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

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

like image 39
Dale Myers Avatar answered May 14 '23 17:05

Dale Myers