问题
How to use a%b
with big integers?
like
...
BigInteger val = new BigInteger("1254789363254125");
...
boolean odd(val){
if(val%2!=0)
return true;
return false;
...
Eclipse says that operator % is undefined for BigInteger.
Any ideas?
回答1:
Like this:
BigInteger val = new BigInteger("1254789363254125");
public boolean odd(BigInteger val) {
if(!val.mod(new BigInteger("2")).equals(BigInteger.ZERO))
return true;
return false;
}
Or as user Duncan suggested in a comment, we can take out the if statement altogether like so:
BigInteger val = new BigInteger("1254789363254125");
public boolean odd(BigInteger val) {
return !val.mod(new BigInteger("2")).equals(BigInteger.ZERO));
}
回答2:
A much more efficient way is to check the last bit. If it is 0
(aka false
) the number is even, otherwise it is odd.
public boolean odd(BigInteger i){
return i.testBit(0);
}
odd(BigInteger.valueOf(1));//true
odd(BigInteger.valueOf(2));//false
odd(BigInteger.valueOf(101));//true
odd(BigInteger.valueOf(100));//false
Also its less lines of code.
回答3:
I'd use the method remainder of the class BigInteger in this way:
BigInteger result = a.remainder(b);
The assignment is due to the fact that BigInteger is immutable, so a won't be changed by the method.
回答4:
Use val.mod(2).
BigInteger is an object. You can't use arithmetic operators on objects, that works only with primitives.
% only works with java.lang.Integer because that is implicitly cast (actually, it is called unboxed) to int. But BigInteger can not be unboxed. unboxing / baxing (that means object to primitive / primitive to object conversion) only works with int, float, double, short and byte.
回答5:
As BigInteger is a class and not a primitive*1, you do not use operators with it. Check the methods for BigInteger: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html#mod(java.math.BigInteger)
*1: In the case of Integer, Float, you can use operators because the JVM automatically converts the object to its primitive value (autoboxing)
来源:https://stackoverflow.com/questions/11586166/operator-for-biginteger-in-java