Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, comparing BigInteger values

Tags:

java

BigInteger bigInteger = ...;


if(bigInteger.longValue() > 0) {  //original code
    //bigger than 0
}

//should I change to this?
if(bigInteger.compareTo(BigInteger.valueOf(0)) == 1) {
    //bigger than 0
}

I need to compare some arbitary BigInteger values. I wonder which approach is correct. Given the above code which one should be used? The original code is on the top.. I am thinking to change it to the second approach.

like image 926
Rosdi Kasim Avatar asked Sep 06 '25 03:09

Rosdi Kasim


1 Answers

The first approach is wrong if you want to test if the BigInteger has a postive value: longValue just returns the low-order 64 bit which may revert the sign... So the test could fail for a positive BigInteger.

The second approach is better (see Bozhos answer for an optimization).

Another alternative: BigInteger#signum returns 1 if the value is positive:

if (bigInteger.signum() == 1) {
 // bigger than 0
}
like image 145
Andreas Dolk Avatar answered Sep 08 '25 00:09

Andreas Dolk