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

When checking 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 correctly pointed out that mod does not accept a negative module. Suppose b positive in your answer.

+5
source share
4 answers

The difference between these methods is documented in Javadoc. From mod(m) :

This method differs from remainder in that it always returns a non-negative BigInteger.

In addition, this method throws an ArithmeticException if this argument is negative, which is not your case according to your change. Thus, to check the divisibility, there will be no difference between mod and remainder : when one of them is 0, the other will be 0. You could just use remainder , since mod can do another calculation that you do not 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 (ie the remainder) + 3 } 

This is actually the same difference for the primitive int a and b and the calculation of a % b (which behaves like remainder ) and Math.floorMod(a, b) (which behaves like mod ).

+5
source

Looking for javadocs ..

For Mod (BigInteger m):

Returns BigInteger whose value ( this mod m ). This method differs from the remainder in that it always returns a non-negative BigInteger.

+3
source

These are different operations. You can see from the JavaDoc, that mod() does not work with zero or negative arguments. You may find this article helpful: http://www.sitecrafting.com/blog/modulus-remainder/

+1
source

They behave differently if b negative. Use any operation you intend to use.

0
source

Source: https://habr.com/ru/post/1245255/


All Articles