% operator for BigInteger in java

£可爱£侵袭症+ 提交于 2019-11-29 09:33:26

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

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.

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.

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.

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!