Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

% operator for BigInteger in java

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?

like image 550
Saendra Avatar asked Jul 20 '12 19:07

Saendra


People also ask

How does BigInteger work in Java?

BigInteger represents immutable arbitrary-precision integers. It is similar to the primitive integer types but allows arbitrary large values. It is used when integers involved are larger than the limit of long type. For example, the factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000.

How do I return BigInteger in Java?

and(BigInteger val) method returns a BigInteger whose value is bitwise-AND of two BigIntegers. This method returns a negative number if both of the BigIntegers are negative. The and() method applies bitwise-AND operation upon the current bigInteger and bigInteger passed as parameter.

What is BigInteger one?

BigInteger. An object whose value is one (1).


1 Answers

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));
}
like image 79
jrad Avatar answered Sep 30 '22 18:09

jrad