Is there an efficient way to get the least non-negative residue modulo n, where n is positive, in C?
This is quite easy if the number is non-negative, then it\'s jus
Few processors implement remainder in hardware, rather it's synthesized from a division and a multiplication. So this is not really a cumbersome reimplementation from the machine's standpoint:
int qm = n / m * m; // a positive or negative multiple of m, rounded up or down
if ( qm <= n ) return n - qm; // usual definition of %
else return n - qm + m; // most common definition of -%, with adjustment
Micro-optimization of the conditional +
may also be beneficial. This could be faster or slower on your machine, but it will work:
int rem = n - n / m * m;
return rem + m & -( rem < 0 );
Total cost: one regular modulo plus one right-shift (to generate -(rem<0)
), one bitwise and, and one add.