Java – should I use mod or remainder when checking the separability of BigInteger?
When a BigInteger B checks the divisibility of BigInteger a, I can write a. mod (b) Equals (BigInteger. Zero) or A. holder (b) equals(BigInteger.ZERO).
Which two expressions are more effective?
Editor: several people correctly pointed out that mod does not accept negative modulus Please assume that B is a positive number in the answer
Solution
The differences between these methods are documented in Javadoc Start with mod (m):
In addition, if the given parameter is negative, this method throws an arithmeticexception. According to your editing, this is not your case Therefore, to test separability, there is no difference between mod and remainder: when one is 0, the other is 0 You can use the remainder because mod can do another calculation you don't need
To understand 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 original int a and B with the calculation of% B (which behaves like a remainder) and math Floormod (a, b) (whose behavior is similar to mod)