Modular math in Java (a numerical line that flows around)

I am trying to create a simple function that uses modular arithmetic . This is essentially a series of lines that wrap around. In particular, I want to use the Mod 8 line number in Java.

I want to compare two numbers between 0 and 7. I want to subtract these numbers to get an estimate of the difference. However, instead of 0-7 = -7, I want it to be 1. The idea is that after reaching 7, the number line wraps back to 0 (so 0 and 7 are only one space across.)

Are there any packages that meet this criterion?

+3
source share
5 answers

, % modulo. , , , . Modulo plus = (a + b)% 8;

+1

((0-7)+8) % 8? .

:% - .

+5

, , . , . , :

-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7

, :

1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

, (, -15, -20, -27, -7), , :

int m = x % 8;
m = (m < 0) ? m + 8 : m;

, , , .

- :

int m = ((x % 8) + 8) % 8

-7 7. , , , , 7. , 0 7. , .

+4

modulo - , . % Java, modulo, . . . , , , . , Wikipedia .

For you to "wrap around" you need a mathematical version of modulo, which, unfortunately, is not implemented in Java for Integer. However, the BigInteger class has a mod () function that does exactly what you need:

BigInteger.valueOf(0-7).mod(BigInteger.valueOf(8)).longValue()

This is not very, but it works.

0
source

Um ... there is a built-in modular module %that is also present mainly in any other language that is generally popular these days.

-1
source

Source: https://habr.com/ru/post/1783264/


All Articles