When checking a BigInteger
a
for divisibility by some BigInteger
b
, I can write either a.mod(b).equals(BigInteger.ZERO)
or a.remainder(b).equals(BigInteger.ZERO)
.
Which of the two expressions is more efficient?
EDIT: Several people have correctly pointed out that mod
doesn't accept a negative modulus. Please assume that b
is positive in your answer.
The difference between those methods is documented in the Javadoc. From mod(m)
:
This method differs from
remainder
in that it always returns a non-negative BigInteger.
Also, this method throws a ArithmeticException
if the given argument is negative, which, as per your edit, is not your case. As such, to test for divisibility, there will be no difference between mod
and remainder
: when one of them is 0 the other will also be 0. You could just use remainder
since mod
can make another calculation that you don't need.
To see the difference in action, consider the following:
public static void main(String[] args) {
BigInteger a = BigInteger.valueOf(-2);
BigInteger b = BigInteger.valueOf(3);
System.out.println(a.remainder(b)); // prints -2
System.out.println(a.mod(b)); // prints 1 == -2 (i.e. the remainder) + 3
}
This is actually the same difference for primitive int
a
and b
and calculating a % b
(which behaves like remainder
) and Math.floorMod(a, b)
(which behaves like mod
).
Looking at the javadocs..
For Mod(BigInteger m):
Returns a BigInteger whose value is (
this mod m
). This method differs from remainder in that it always returns a non-negative BigInteger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With