Search code examples
modular-arithmetic

Is there a shorthand for modulation in reverse?


Say I have array indices 0 through 5

If I'm incrementing a counter over this array, I could do something like

i % 6

To make sure it never goes out of index. Is there a shorthand notation for the same thing for decrementing? I'm asking in general, not specific to any language

I know I can do

if (i < 0) i = 5

Solution

  • For positive integer n and non-negative counter i, you can define increment and decrement of the counter modulo n as arithmetic operations with positive integer values. Increment is i = (i + 1) % n, and decrement is i = (i + n - 1) % n.