在检查BigInteger的可分性时,我应该使用mod还是余数?

时间:2016-03-17 17:22:38

标签: java biginteger

某些BigInteger a检查BigInteger b是否可以分割时,我可以写a.mod(b).equals(BigInteger.ZERO)a.remainder(b).equals(BigInteger.ZERO)

这两个表达式中的哪一个更有效?

编辑:有几个人正确地指出mod不接受负模数。请假设您的答案中b为肯定。

4 个答案:

答案 0 :(得分:6)

这些方法之间的区别记录在Javadoc中。来自mod(m)

  

此方法与remainder的不同之处在于它始终返回非负BigInteger。

此外,如果给定的参数为负数,此方法将抛出ArithmeticException,根据您的编辑,这不是您的情况。因此,为了测试可分性,modremainder之间没有区别:当其中一个为0时,另一个也为0.您可以使用remainder,因为{ {1}}可以进行另一种您不需要的计算。

要了解行动的不同,请考虑以下事项:

mod

对于原始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 } inta以及计算b(其行为类似于a % b)和Math.floorMod(a, b),这实际上是相同的差异(其行为类似于remainder)。

答案 1 :(得分:3)

看着javadocs ..

对于Mod(BigInteger m):

  

返回值为(this mod m)的BigInteger。此方法与其余方法的不同之处在于它始终返回非负 BigInteger。

答案 2 :(得分:1)

这些是不同的操作。您可以从JavaDoc中看到mod()没有使用零或负参数。您可以在本文中找到有用的信息:http://www.sitecrafting.com/blog/modulus-remainder/

答案 3 :(得分:0)

如果b为否定,则表现不同。使用您打算使用的任何操作。