# Mod of Negative Numbers

• 01-28-2011, 05:04 AM
Venny
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
• 01-28-2011, 05:08 AM
Junky
That is the correct output. On the other hand if you always want a positive result use the Math.abs method.
• 01-28-2011, 05:12 AM
Venny
is that the same with C/C++ as well. and how does the Math.abs method work?

Thanks
• 01-28-2011, 05:16 AM
Junky
Is what the same as c/c++?
Quote:

how does the Math.abs method work
How about you read what the method does in the API.
• 01-28-2011, 05:24 AM
pbrockway2
Quote:

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".
• 01-28-2011, 05:35 AM
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.
• 01-28-2011, 05:37 AM
gcalvin
Quote:

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-
• 01-28-2011, 06:32 AM
Venny
@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?