Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use mod or remainder when checking a BigInteger for divisibility?

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.

like image 432
sjakobi Avatar asked Mar 17 '16 17:03

sjakobi


2 Answers

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).

like image 76
Tunaki Avatar answered Sep 19 '22 11:09

Tunaki


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.

like image 29
Ldvg Avatar answered Sep 21 '22 11:09

Ldvg