This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt 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 Introducing JavaFX 8 Programming this week in the JavaFX 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: 4086
    
  18

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.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
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: 44433
    
  33
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: 4086
    
  18

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Modular arithmetic
 
It's not a secret anymore!