Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger.pow(BigInteger)?

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.

like image 841
PeterW Avatar asked Jan 03 '11 05:01

PeterW


People also ask

What is BigInteger used for?

BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

What is BigInteger C#?

The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. The members of the BigInteger type closely parallel those of other integral types (the Byte, Int16, Int32, Int64, SByte, UInt16, UInt32, and UInt64 types).

What does BigInteger modPow do?

modPow(BigInteger exponent, BigInteger m) returns a BigInteger whose value is (thisexponent mod m). Unlike pow, this method permits negative exponents.

How does BigInteger calculate power in Java?

Use the BigInteger pow() method in Java to calculate the power on a BigInteger.


2 Answers

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.

like image 193
Keith Randall Avatar answered Sep 21 '22 15:09

Keith Randall


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.

like image 31
Raul Rene Avatar answered Sep 21 '22 15:09

Raul Rene