In JavaScript, C and C++,

and let the magic of modular arithmetic do its work. This works for unsigned integers too.

`x % y`

will return a negative number if x is negative. This isn't what you want if you're trying to wrap around an array index (for example). Fortunately there's a nice solution. Instead of writing something like this:int prev(int x, int N) { int prevX = (x - 1) % N; if (prevX < 0) prevX = N - 1; return prevX; }you can simply write:

int prev(int x, int N) { return (x + N - 1) % N; }

and let the magic of modular arithmetic do its work. This works for unsigned integers too.

## Comments

## Post a Comment