This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Modular arithmetic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Modular arithmetic " Watch "Modular arithmetic " New topic
Author

Modular arithmetic

Ernie Mcracken
Ranch Hand

Joined: Feb 13, 2011
Posts: 33

Hi,

Doe's anyone know how to do modular arithmetic in Java ? I need to do modular subtraction so using the % operator is out of the window.

Cheers

Ernie


You're on a gravy train with biscuit wheels Roy.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3658
    
  17

Hmm I'm sure there is a shorter way of doing this, but if I think quickly, you could perform subtraction like so:

Where val is the minuend, mod is the modulus, and sub is the subtrahend.
Ernie Mcracken
Ranch Hand

Joined: Feb 13, 2011
Posts: 33

That seems to work nicely, thanks very much. I did notice that you can do it with BigInteger but that would be a pain to implement in my code.

Thanks again.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 41091
    
  29
Stephan van Hulst wrote: . . . . . .
Should that read . . . instead?

And it is by no means difficult to use BigInteger. You simply have to try it.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3658
    
  17

Not that I know. Why?yields a positive number that is the 'inverse' of sub. If you add this number to you original value, it will wrap around as if you subtracted.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Modular arithmetic