Author
Modular arithmetic
Ernie Mcracken
Ranch Hand
Joined: Feb 13, 2011
Posts: 33
posted Mar 28, 2011 10:04:10
0

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: 3694
posted Mar 28, 2011 10:59:05
0

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
posted Mar 28, 2011 11:04:11
0

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: 41851
posted Mar 29, 2011 03:57:09
0

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: 3694
posted Mar 29, 2011 06:47:12
0

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.
subject: Modular arithmetic