# Thread: Mod of Negative Numbers

1. Member
Join Date
Jan 2011
Posts
24
Rep Power
0

## Mod of Negative Numbers

Hi All,

This may not b a new question to most of you but since am a newbie, please consider answering this.

For languages like c/c++ and java, how does mod % operator work with negative numbers.

for e.g and trying to fetch the output of -3%2 . The actual output is -1 whereas it should be just 1.

Could you help me to come out with a solution on how shall I generate the correct output for negative numbers.

thanks

2. That is the correct output. On the other hand if you always want a positive result use the Math.abs method.

3. Member
Join Date
Jan 2011
Posts
24
Rep Power
0
is that the same with C/C++ as well. and how does the Math.abs method work?

Thanks

4. Is what the same as c/c++?
how does the Math.abs method work

5. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
15
The actual output is -1 whereas it should be just 1.

Stop and think about that statement for a moment. The output is -1, that's all. Unless the compiler and runtime authors have made a mistake (and they haven't) then it is just what it should be.

What it should be in the case of Java is described authoratively in the JLS: in the section 15.17.3 Remainder Operator %. They give a motivation there (that a%b should be such that (a/b)*b+(a%b) is equal to a) but it is the inclusion of that section in the JLS that makes -1 what -3%2 should just be.

Other languages may define a notion of modulus which is similar but different. For instance in C++ "the binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined".
Last edited by pbrockway2; 01-28-2011 at 05:26 AM.

6. Member
Join Date
Jan 2011
Posts
24
Rep Power
0
Ohh I c.. but as per math notations, there is nothing like negative mod. mod should always be greater than zero. So I belive, the operator % is not exactly used as mod in Java.

7. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
7
Originally Posted by Venny
Ohh I c.. but as per math notations, there is nothing like negative mod. mod should always be greater than zero. So I belive, the operator % is not exactly used as mod in Java.
That's correct, and it's not called the modulus operator, it's called the remainder operator -- for that very reason.

-Gary-

8. Member
Join Date
Jan 2011
Posts
24
Rep Power
0
@Junky : I meant to ask if the % operator works same as in C/C++ too and if they hve different implementation then how can we generate the correct output?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•