File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Using Modulus Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using Modulus" Watch "Using Modulus" New topic

Using Modulus

John Daniels

Joined: May 09, 2006
Posts: 4
When using the modulus, if a<b, then a%b = a. But why, if a is negative, does -a%b = -a? According to the division algorithm, the remainder r must be >= 0 and <|b|.
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
The formula Java use for integral modulo operations is

Let's see some examples:

Case 1: Positive Numbers -> 7 % 2

Conclusion: Positive yield possitive

Case 2: Negative Divisor -> 7 % -2

Conclusion: Negative divisor yields positive results.

Case 3: Negative dividend -> -7 % 2

Conclusion: Negative dividend yields negative results

Case 4: Negative dividend and divisor -> -7 % -2

Conclusion: Only negative dividend affect the result
[ May 09, 2006: Message edited by: Edwin Dalorzo ]
John Daniels

Joined: May 09, 2006
Posts: 4
I agree. Here's the link:
subject: Using Modulus
It's not a secret anymore!