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)}. $$

  • $\begingroup$ This is exactly what I was looking for. Thanks! $\endgroup$ – Adam Barnett Jul 18 '17 at 18:42
  • $\begingroup$ 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. $\endgroup$ – fade2black Jul 18 '17 at 18:53
  • 2
    $\begingroup$ @fade2black Fortunately, this formula only involves non-negative integers. $\endgroup$ – 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$.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.