The standard way I learned is
inline int positive_modulo(int i, int n) {
return (i % n + n) % n;
}
This function is essentially your first variant without the abs
(which, in fact, makes it return the wrong result). I wouldn’t be surprised if an optimizing compiler could recognize this pattern and compile it to machine code that computes an “unsigned modulo”.
Edit:
Moving on to your second variant: First of all, it contains a bug, too — the n < 0
should be i < 0
.
This variant may not look as if it branches, but on a lot of architectures, the i < 0
will compile into a conditional jump. In any case, it will be at least as fast to replace (n * (i < 0))
with i < 0? n: 0
, which avoids the multiplication; in addition, it’s “cleaner” because it avoids reinterpreting the bool as an int.
As to which of these two variants is faster, that probably depends on the compiler and processor architecture — time the two variants and see. I don’t think there’s a faster way than either of these two variants, though.