# Is there an algorithm for a number line from $0$ to $n$

Where $n + 1 = 0$ and $0 - 1 = n$?

The $n + 1 = 0$ case can be achieved by using the modulus operator, but I can't figure out how to treat the $0 - 1 = n$ case.

For $a,b \in \{0,\ldots,n\}$, subtraction is given by $$a - b = [a + (n+1-b)] \bmod{(n+1)}.$$

• This is exactly what I was looking for. Thanks! – Adam Barnett Jul 18 '17 at 18:42
• But you should be careful when implementing it using a programming language. Python and Ruby will evaluate (0 - 20) % 13 as 6 while C++ will output -7. – fade2black Jul 18 '17 at 18:53
• @fade2black Fortunately, this formula only involves non-negative integers. – Yuval Filmus Jul 18 '17 at 19:07

You could simply compute $(a - b) \bmod{(n+1)}$. But you should also be aware of the least positive remainder and the least absolute remainder. Some libraries/languages may output the least positive remainder (for example Ruby and Python), while others may output the least absolute remainder like in C++. In the later case if the remainder is negative you simply add it to $n+1$.