某些BigInteger
a
检查BigInteger
b
是否可以分割时,我可以写a.mod(b).equals(BigInteger.ZERO)
或a.remainder(b).equals(BigInteger.ZERO)
。
这两个表达式中的哪一个更有效?
编辑:有几个人正确地指出mod
不接受负模数。请假设您的答案中b
为肯定。
答案 0 :(得分:6)
这些方法之间的区别记录在Javadoc中。来自mod(m)
:
此方法与
remainder
的不同之处在于它始终返回非负BigInteger。
此外,如果给定的参数为负数,此方法将抛出ArithmeticException
,根据您的编辑,这不是您的情况。因此,为了测试可分性,mod
和remainder
之间没有区别:当其中一个为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
}
int
和a
以及计算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
为否定,则表现不同。使用您打算使用的任何操作。