How invert this formula with % operator

113 Views Asked by At

I have a semaphore variable with 5 states.

I can increase the state using this cicle

X = (X + 1) % 5

For X = {0, 1, 2, 3, 4} generate {1, 2, 3, 4, 0}.

But if I try go in the other direction decreasing the state, doesn't bring the right result.

X = (X - 1) % 5

For X = {0, 1, 2, 3, 4} generate {-1, 0, 1, 2, 3} insted of {4, 0, 1, 2, 3}

For example in excel if you try =MOD(-1;5) you get 4.

2

There are 2 best solutions below

6
On BEST ANSWER

Instead of

X = (X - 1) % 5

use

X = (X + 4) % 5

which is the short form of

X = (X - 1 + 5) % 5

or generally

X = (X - 1 + n) % n

This ensures that the argument in () is always positive - so the division remainder stays also positive.

2
On

The problem is caused by the fact that C# supports remainder operator instead of modulus operator.

If your x is always in the range between 0 and n-1 then the other simpler solutions suffice. If you want a method that works for any x then something more complicated is necessary.

static int modulus(int x, int n)
{
    return ((x % n) + n) % n;
}

The first remainder operation converts the value to the -n+1 ... n-1 range. Once we add n we obtain always positive value. The final remainder operation then provides the expected result.