Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Modular arithmetic

 
Ernie Mcracken
Ranch Hand
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stephan van Hulst
Bartender
Pie
Posts: 5589
54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5589
54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic