Results 1 to 8 of 8
Thread: Mod of Negative Numbers
 01282011, 05:04 AM #1Member
 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
 01282011, 05:08 AM #2
That is the correct output. On the other hand if you always want a positive result use the Math.abs method.
 01282011, 05:12 AM #3Member
 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
 01282011, 05:16 AM #4
Is what the same as c/c++?
how does the Math.abs method work
 01282011, 05:24 AM #5Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,712
 Rep Power
 14
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 implementationdefined".Last edited by pbrockway2; 01282011 at 05:26 AM.
 01282011, 05:35 AM #6Member
 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.
 01282011, 05:37 AM #7Senior Member
 Join Date
 Mar 2010
 Posts
 952
 Rep Power
 7
 01282011, 06:32 AM #8Member
 Join Date
 Jan 2011
 Posts
 24
 Rep Power
 0
Similar Threads

Help with negative numbers
By cela0811 in forum New To JavaReplies: 2Last Post: 01042011, 06:04 PM 
Byte value comes out negative
By Bluefox815 in forum New To JavaReplies: 1Last Post: 07032010, 03:52 AM 
string to negative int problem
By pendulum101 in forum New To JavaReplies: 5Last Post: 11012009, 06:47 PM 
I don't want negative money [BUG]
By anthonym2121 in forum New To JavaReplies: 1Last Post: 04072009, 08:06 AM 
Negative elements
By swikar.java in forum New To JavaReplies: 6Last Post: 12152008, 05:48 AM
Bookmarks