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...
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...
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.
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.
You can use pow, but left shift is likely to be faster.
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.