问题
Consider the following expression:
(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
Also, how is (-b mod N) calculated, i.e., how is the mod of a negative number calculated?
Thanks.
回答1:
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.
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.
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.
An example here in pseudocode :
function mod (int a, int N)
return (a%N+N)%N
回答2:
answer is option a
see for explanation
http://naveensnayak.wordpress.com/2009/12/21/modulus-of-negative-numbers/
http://answers.yahoo.com/question/index?qid=20080922034737AAsFEfY
回答3:
while(N < 0)
{
N= N+MOD;
}
Or,
This will also work,
int mod(num ,modValue)
{
return ( modValue- ( (-num) % modValue) );
}
来源:https://stackoverflow.com/questions/19264015/modulo-of-a-negative-number