aspose file tools*
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
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: 3649
    
  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: 40061
    
  28
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: 3649
    
  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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Modular arithmetic