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

前端 未结 4 1377
抹茶落季
抹茶落季 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

    You could simply check if the result is negative and then act accordingly:

    int mod(int n, int m) {
       int r = n % m;
       if (r < 0)
          return r + m;
       else
          return r;
    }
    

    Or, without if-then-else and as a single expression:

    r = ((n % m) + m) % m;
    

提交回复
热议问题