Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modular Math in Java (Number Line which Wraps Around)

I am trying to create a simple function that utilizes modular arithmetic. This is essentially a number line that wraps around. Specifically I want to use a Mod 8 number line in Java.

What I want is to compare two numbers between 0 and 7. I want to subtract these numbers to get a difference score. However, instead of 0-7=-7, I want it to equal 1. The idea being that after you reach 7, the number line wraps around back to 0 (therefore 0 and 7 are only one space across.)

Are there any packages that fit this criterion?

like image 591
Spencer Avatar asked Dec 15 '25 10:12

Spencer


1 Answers

how about ((0-7)+8) % 8 ? This should fix up your case.

Note: % is the Modular operator.

like image 112
Faisal Feroz Avatar answered Dec 16 '25 22:12

Faisal Feroz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!