Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Modular arithmetic  RSS feed

 
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
Saloon Keeper
Posts: 7806
142
  • 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
Marshal
Posts: 55698
163
  • 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
Saloon Keeper
Posts: 7806
142
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!