What is an efficient way to get the least non-negative residue modulo n in C?

前端 未结 4 1343
抹茶落季
抹茶落季 2021-01-19 05:18

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

4条回答
  •  旧时难觅i
    2021-01-19 05:47

    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.

提交回复
热议问题