BigInteger.pow(BigInteger)? - java

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.

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.

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.

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.

Please be sure to read the previous answers and comments and understand why this should not be attempted on a production level application. The following is a working solution that can be used for testing purposes only:
Exponent greater than or equal to 0
BigInteger pow(BigInteger base, BigInteger exponent) {
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ZERO; i.compareTo(exponent) != 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(base);
}
return result;
}
This will work for both positive and negative bases. You might want to handle 0 to the power of 0 according to your needs, since that's technically undefined.
Exponent can be both positive or negative
BigDecimal allIntegersPow(BigInteger base, BigInteger exponent) {
if (BigInteger.ZERO.compareTo(exponent) > 0) {
return BigDecimal.ONE.divide(new BigDecimal(pow(base, exponent.negate())), 2, RoundingMode.HALF_UP);
}
return new BigDecimal(pow(base, exponent));
}
This re-uses the first method to return a BigDecimal with 2 decimal places, you can define the scale and rounding mode as per your needs.
Again, you should not do this in a real-life, production-level system.

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.

2^2,147,483,647 has at least 500000000 digit, in fact computing pow is NPC problem, [Pow is NPC in the length of input, 2 input (m,n) which they can be coded in O(logm + logn) and can take upto nlog(m) (at last the answer takes n log(m) space) which is not polynomial relation between input and computation size], there are some simple problems which are not easy in fact for example sqrt(2) is some kind of them, you can't specify true precision (all precisions), i.e BigDecimal says can compute all precisions but it can't (in fact) because no one solved this up to now.

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);

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

Just use .intValue()
If your BigInteger is named BigValue2, then it would be BigValue2.intValue()
So to answer your question, it's
BigValue1.pow(BigValue2.intValue())

Related

I am trying to take 1020 to the 275th power, and modding that by 1073, but java wont output the right answer

i am working on a decoder, and i need to take 1020 to the 275th power, and mod that by 1073, but when i do try that, it wont print out the correct answer
double decoded = (1020^275)%1073;
That is the code i am trying, but it will print out 751, and its supposed to print 4, anyone have any tips?
^ is the xor operator; however, 1020 to the 275th power is a HUGE number and will overflow even if using double or long, so it should be represented by BigInteger:
System.out.println(BigInteger.valueOf(1020).pow(275).mod(BigInteger.valueOf(1073)));
Output:
4
Note: I used BigInteger#mod, but BigInteger#remainder will return the same value in your case (as you're only dealing with non-negative values).
You can use BigInteger.pow() followed by BigInteger.mod().
However the BigInteger class specifically includes in operation for your task: BigInteger.modPow():
System.out.println(BigInteger.valueOf(1020).modPow(BigInteger.valueOf(275), BigInteger.valueOf(1073)));
gives 4.
Try this out:
BigDecimal remainder = new BigDecimal(1020).pow(275).remainder(new BigDecimal(1073));
System.out.println(remainder);
After applying remainder, it can be converted to long as its max value will be 1072(in this case):
remainder.longValueExact();
double is bounded and has precision limitations, try:
System.out.println(Math.pow(1020, 275)); // Infinity
Usually, you should use BigDecimal or BigInteger to manipulate big numbers,
BigDecimal bigDecimal = new BigDecimal(1020);
bigDecimal = bigDecimal.pow(275);
bigDecimal = bigDecimal.remainder(new BigDecimal(1073));
System.out.println(bigDecimal); //4
Xor is differ from power function. 2 ^ 3, The output of an XOR gate is true only when exactly one of its inputs is true. If both of an XOR gate's inputs are false, or if both of its inputs are true, then the output of the XOR gate is false.
double maximum value = 1.7976931348623157E308
Actually (1020^275) = 2.3176467070363862212063591722218e+827 which greater than double maximum value.
Go with BigDecimal.
System.out.println(new BigDecimal(1020.0).pow(275).remainder(new BigDecimal(1073)));

Taking Modulo of Double NUmber

I have given two number a and b.I have to Calculate (a^b)%1000000007.How Can i calculate for floating point numbers. Ex:
a= 7.654 and b=10000
Here is my Code will % work :
public static double super_pow(double A , long B){
double o=1;
while(B>0){
if((B&1)!=0) o*=A;
A*=A;
B/=2;
o%=mod;
A%=mod;
}
return (o)%mod;
}
Yes, in Java you can use the % operator on floating point types.
You will have problems with the exponent though: You can't use % to reduce the intermediate results because modulo does not distribute over floating point multiplication: (a*b)%c is not (a%c)*(b%c). If you try to compute 7.654^10000 directly you will get infinity; it exceeds the maximum value for double. Even if it didn't you couldn't trust the lowest digits of the result because they are pure noise created by rounding and representation error.
You could use a library that implements exact arithmetic, such as java.math.BigDecimal, but that will cost a lot in terms of execution time and memory. If you think you need to do this calculation as a part of a bigger problem, probably you should take a step back and find another way.
Edit: Here's the result with BigDecimal:
BigDecimal[] divmod = new BigDecimal("7.654").pow(10000)
.divideAndRemainder(new BigDecimal("1000000007"))
return divmod[1].doubleValue() // I get 9.01287592373194E8
In java you can use the modulo operation for floats/doubles (How do I use modulus for float/double?)
If you have to calculate (a^b)%1000000007 you can use double for a and b
(biggest integer that can be stored in a double), this makes exponentiation easier, use the pow() method (http://www.tutorialspoint.com/java/number_pow.htm)
import static java.lang.Math.pow;
public static double super_pow(double A , double B){ //returns long and B is also double
double pow;
double mod = 1000000007.0;
pow = Math.pow(A,B);
mod = pow % 1000000007;
return mod;
}
Alternatively you can typecast (loss of precision possible !) the result of a^b to long and then use
double pow = Math.pow(A,B);
long mod = (long) pow%1000000007L; // the 'L' is important see https://stackoverflow.com/questions/5737616/what-is-the-modulo-operator-for-longs-in-java
return mod; //return a long not double in function
What is the modulo operator for longs in Java?
Is % Modulo?
That depends on language you are using. But In general floating point values does not know modulo operation. You can compute it on your own. Let assume positive floating numbers a=7.654 and b=10000.0 so
d = a/b = 0.0007654 // division
r = d-floor(d) = (0.0007654-0.0) = 0.0007654 // remainder
r = r*b = (0.0007654*10000.0) = 7.654 // rescale back
floor(x) rounds down to nearest less or equal number to x
d holds the floating division result
r holds the remainder (modulo)
Another example a=123.456 and b=65
d = a/b = 1.8993230769230769230769230769231
r = (d-floor(d))*b = 58.456
This can be used for integer and decimal values of a,b but beware the floating point unit performs rounding and can loose precision after few digits... If I remember correctly 64 bit double variables are usually usable maximally up to 18 digits.
[Edit1] hmm you reedited the question to completely different problem
So you are searching for modpow. You can google for java implementation of modpow. For example here
Modular arithmetics and NTT (finite field DFT) optimizations
You can find mine implementation in C++ on 32 bit integer arithmetics but with static modulo prime with specific properties. Still if you change all the
if (DWORD(d)>=DWORD(p)) d-=p;
to d=d%p; it would work for any modulo. you will need modpow,modmul,modadd,modsub.

BigInteger power of a BigDecimal in Java

I tried to get the power of a double value where the exponent is very large (Java BigInteger can contain it (the exponent), for example: 10^30)
That is, I want to find something like 1.75^(10^30) or 1.23^(34234534534222).if the output is too large modify it by getting the modulus by a prime like 10^9+7.
If I want to find a power of an Integer I can use BigInteger.modPow() method which take BigInteger arguments:
( BigInteger modPow(BigInteger exponent, BigInteger m) )
As far as i can go this is what i got in Java
new BigDecimal("1.5").pow(1000); // .pow() can get only integers as a parameter , but i want to pass a big number like a BigInteger
I cannot find an equivalent for that (BigInteger.modPow()) in java for BigDecimal
, or i'm missing that.
Are there any ways to do that - Calculate a large power of a floating point number (a Decimal)?
Example of input and output :
Input : num // or 1.5 or any decimal number. can be an integer also.
exponent : exp // big integer or a Long value
output : num^exp // num to ther power exp
i.e like calculating 1.23^(34234534534222)
if the output is too large modify it by getting the modulus by a prime like 10^9+7
There is a Math.BigDecimal implementation of core mathematical functions which has:
static java.math.BigDecimal powRound(java.math.BigDecimal x, java.math.BigInteger n)
Raise to an integer power and round.
which seems exactly what you need. The fact that there is an external library for it denotes that there is no core implementation of a method like this in java.Math.
As a side note I can say that if your input is considerably small in terms of decimal places (thus no irrational) just like 1.5 you can transform it in 15/10 and do
(15^BigInteger)/(10^BigInteger)
with the modPow(BigInteger exponent, BigInteger m) of BigInteger. This obviously raises the complexity and the numbers to calculate.
There are several caveats. As Gábor Bakos pointed out, the resulting value would most likely contain too many digits to even be represented as a BigDecimal.
Additionally, these number of digits grows quickly, so computing something like 2.034234534534222 is completely out of scope in terms of storage (and, as I assume, in terms of required time).
You mentioned that the value may be computed modulo a large prime when it becomes "too large". Although you did not say what exactly this means, this won't necessarily help you here, because using modulo will not truncate the decimal places. You'll somehow have to limit the precision in which the computation takes place.
However, the most simple implementation using exponentiation by squaring could roughly look like this:
import java.math.BigDecimal;
import java.math.BigInteger;
public class BigDecimalPow {
public static void main(String[] args) {
BigDecimal b = new BigDecimal(1.5);
BigInteger e = new BigInteger("325322");
BigDecimal result = pow(b, e);
System.out.println("Done "+result.scale());
System.out.println(result);
}
/**
* Computes d to the power of e
* #param b The value
* #param e The exponent
* #return The power
*/
private static BigDecimal pow(BigDecimal b, BigInteger e) {
BigDecimal result = BigDecimal.ONE;
BigDecimal p = b;
int skipped = 0;
while (e.compareTo(BigInteger.ZERO) > 0) {
if (e.and(BigInteger.ONE).equals(BigInteger.ONE)) {
if (skipped > 0) {
if (skipped > 29) {
p = pow(p, BigInteger.ONE.shiftLeft(skipped));
} else {
p = p.pow(1 << skipped);
}
skipped = 0;
}
result = result.multiply(p);
}
skipped++;
e = e.shiftRight(1);
System.out.println(e);
}
return result;
}
}
Note: The implementation above is really simple. There most likely is a solution that is more efficient for some cases, or uses the modulo operation to support "larger" numbers. But you simply can not represent (potentially) 34234534534222 decimal places unless you have 34 terabytes of RAM and a JVM with long addressing, so I doubt that there will be a solution that satisfies the requirements that you stated until now - but would upvote+bounty anyone who proved me wrong...

Divide big integer number to get exact value

I am trying to find the value of 1/(2^n) where 0 <=n<= 200
I have tried to use biginteger but it is giving output as zero . I want exact number after division .
import java.math.BigInteger;
public class Problem2 {
public static void main(String args[]){
BigInteger bi1 = new BigInteger("2").pow(200);
BigInteger bi2 = BigInteger.ONE;
BigInteger bi3 = bi2.divide(bi1);
System.out.println(bi3); //why it giving output zero
}
}
On use of BigDecimal it is giving exponential value , but how to get exact value without exponent.
because 0< bi3 <1, so an integer result is 0. Try BigDecimal in place of BigInteger
BigInteger works like Integer in that the result of calculations between two integers is an integer.
If we write int n = 1 / 1024 the result is likewise 0.
Try this:
BigDecimal b = new BigDecimal( new BigInteger("2").pow(200) );
BigDecimal one = new BigDecimal(1);
BigDecimal quotient = one.divide(b);
System.out.println(quotient); //scientific notation. (140 significant digits)
System.out.println(quotient.toPlainString()); //regular notation with leading zeros
The result of 1/(2^200) is going to be extremely small, and definitely not an integer, so the zero result you are getting is "correct".
The answer is so small that even Java double (64 bit) will run out of precision. You may be able to coax BigDecimal to give the correct answer, but the performance will almost certainly be terrible.
Why do you need such precision? The number of atoms in the universe has been estimated at around 10^38, which I think is around 2^150. We can help better if we know what you are trying to do.
Try for float/Double in case you get result in decimal points.

How to do a fractional power on BigDecimal in Java?

In my little project, I need to do something like Math.pow(7777.66, 5555.44) only with VERY big numbers. I came across a few solutions:
Use double - but the numbers are too big
Use BigDecimal.pow but no support for fractional
Use the X^(A+B)=X^A*X^B formula (B is the remainder of the second num), but again no support for big X or big A because I still convert to double
Use some kind of Taylor series algorithm or something like that - I'm not very good at math so this one is my last option if I don't find any solutions (some libraries or formula for (A+B)^(C+D)).
Does anyone know of a library or an easy solution? I figured that many people deal with the same problem...
p.s.
I found some library called ApFloat that claims to do it approximately, but the results I got were so approximate that even 8^2 gave me 60...
The solution for arguments under 1.7976931348623157E308 (Double.MAX_VALUE) but supporting results with MILLIONS of digits:
Since double supports numbers up to MAX_VALUE (for example, 100! in double looks like this: 9.332621544394415E157), there is no problem to use BigDecimal.doubleValue(). But you shouldn't just do Math.pow(double, double) because if the result is bigger than MAX_VALUE you will just get infinity. SO: use the formula X^(A+B)=X^A*X^B to separate the calculation to TWO powers, the big, using BigDecimal.pow, and the small (remainder of the 2nd argument), using Math.pow, then multiply. X will be copied to DOUBLE - make sure it's not bigger than MAX_VALUE, A will be INT (maximum 2147483647 but the BigDecimal.pow doesn't support integers more than a billion anyway), and B will be double, always less than 1. This way you can do the following (ignore my private constants etc):
int signOf2 = n2.signum();
try {
// Perform X^(A+B)=X^A*X^B (B = remainder)
double dn1 = n1.doubleValue();
// Compare the same row of digits according to context
if (!CalculatorUtils.isEqual(n1, dn1))
throw new Exception(); // Cannot convert n1 to double
n2 = n2.multiply(new BigDecimal(signOf2)); // n2 is now positive
BigDecimal remainderOf2 = n2.remainder(BigDecimal.ONE);
BigDecimal n2IntPart = n2.subtract(remainderOf2);
// Calculate big part of the power using context -
// bigger range and performance but lower accuracy
BigDecimal intPow = n1.pow(n2IntPart.intValueExact(),
CalculatorConstants.DEFAULT_CONTEXT);
BigDecimal doublePow =
new BigDecimal(Math.pow(dn1, remainderOf2.doubleValue()));
result = intPow.multiply(doublePow);
} catch (Exception e) {
if (e instanceof CalculatorException)
throw (CalculatorException) e;
throw new CalculatorException(
CalculatorConstants.Errors.UNSUPPORTED_NUMBER_ +
"power!");
}
// Fix negative power
if (signOf2 == -1)
result = BigDecimal.ONE.divide(result, CalculatorConstants.BIG_SCALE,
RoundingMode.HALF_UP);
Results examples:
50!^10! = 12.50911317862076252364259*10^233996181
50!^0.06 = 7395.788659356498101260513
The big-math library released under MIT license has a simple static helper BigDecimalMath.log(BigDecimal, MathContext) for log and many other functions not included with BigDecimal. Very simple to use and has lots of benchmarking data to compare performance.
Exponents = logarithms.
Take a look at Logarithm of a BigDecimal

Categories

Resources