4

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'm voting to close this question as off-topic because it is about math, not programming. Commented May 18, 2015 at 1:38

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
while(N < 0)
{
    N= N+MOD;
}

Or,
This will also work,

int mod(num ,modValue)
{
    return ( modValue- ( (-num) % modValue) );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.