Algorithm for determining the number between two numbers in modular arithmetic

I am trying to write a function that answers the question: if you start counting with a and stop counting in b , this is c in this range (aka c between a and b ).

Usually a < c && c < b enough, but I'm in modular arithmetic:

(Diagram)

Increases counterclockwise.

Greens: these are the values ​​for c, where the algorithm should indicate true (where c is between a and b)

Blue colors: these are the values ​​for c, where the algorithm should indicate false (where c is not between a and b) (which is the same as where c is between b and )

The simple a < c && c < b fails when the range of a and b crosses 0.

For example, say A = 300 and B = 45. If C is 10, the function should return true: 300 , 301, 302 ... 359, 0, 1, 2, 3 ... 8, 9, 10 , 11, 12 ... 43, 44, 45 . Therefore, 10 is between 300 and 45 in 360 mode.

In the end, what I'm trying to determine is one shade between two other shades, where shades are set in degrees around the color wheel (this is a mod 360 system). It would be great if the answer was in terms of mod n, so it would solve the general case and not be specific to my problem.

+6
source share
2 answers

First compute a mod n , b mod n and c mod n .

If a < b , then we need to check that a < c && c < b . This is a simple case when modular arithmetic does not play a huge role.

Since [a, b] and [b, a] form disjoint regions, instead of trying to solve the problem of intersection 0, we can check the opposite for cases where b < a . If b < c && c < a true, c is actually between b and a and therefore not between a and b.

Code example:

 a = a % n; // % = mod b = b % n; c = c % n; if (a < b) { if (a < c && c < b) return true; else return false; } else { // b < a if (b < c && c < a) return false; // if in [b, a] then not in [a, b] else return true; } 
+4
source

A number will be between these two numbers if either of the following three conditions is true.

Condition 1 :

 c mod n > a mod n && c mod n < b mod n 

Condition 2 :

 a mod n > b mod n && c mod n < b mod n. 

Condition 3 :

 a mod n > b mod n && c mod n > a mod n. 
+1
source

All Articles