负数模 [英] Modulo of a negative number
问题描述
考虑以下表达式:
(a - b) mod N
以下哪个与上面的表达式等效?
Which of the following is equivalent to the above expression?
1) ((a mod N) + (-b mod N)) mod N
2) ((a mod N) - (b mod N)) mod N
另外,如何计算(-b mod N),即如何计算负数的mod?
Also, how is (-b mod N) calculated, i.e., how is the mod of a negative number calculated?
谢谢.
推荐答案
我不想打扰您一些复杂的数学概念,因此,我将尝试使其保持简单. 当我们说a = b(mod c)时,我们只是说a-b是c的倍数. 这意味着当我们想知道mod c的值是什么时,说它是a或a-c或a + c或a + 1000 * c是正确的. 因此,您的两个公式是有效的.
I don't want to bother you with some complex mathematical concepts, so i'll try to keep it simple. When we say that a = b (mod c), we simply say that a-b is a multiple of c. This means that when we want to know what is the value of a mod c, saying that it is a or a-c or a+c or a+1000*c is true. Thus, your 2 formulas are valid.
但是您想要的是知道计算机会给您的答案,对吗? 好吧,这取决于您使用的语言. 例如,对于Java,mod b具有a的符号,并且绝对值严格低于b.这意味着a = 7,b = 3且N = 5,(a-b)%N = 4,但是您的两个表达式将返回-1.
But what you want is to know the answer that a computer would give to you, right ? Well, it depends of the language you are using. With Java for example, a mod b has the sign of a and has is absolute value strictly inferior to b. This means that with a = 7, b = 3 and N = 5, (a-b)%N = 4, but your two expressions will return -1.
如果您想对模进行算术运算,我建议您做的是创建自己的mod函数,例如,它总是给您一个正整数.这样,您的2个表达式将始终等于原始表达式.
What I would suggest you to do if you want to do arithmetics with modulos is to create your own mod function, so it always give you a positive integer for example. This way, your 2 expressions will always be equal to the original one.
此处为伪代码示例:
function mod (int a, int N)
return (a%N+N)%N
这篇关于负数模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!