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

前端 未结 4 1376
抹茶落季
抹茶落季 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条回答
  •  醉酒成梦
    2021-01-19 05:31

    Furthermore, in C99 the behaviour is defined to be the annoying one: -2 % 11 = -2.

    In general (i.e., n % m when m is not constant and the range of n is unconstrained), you probably can't do better than the usual

    res = ((n % m) + m) % m
    

    It may be interesting to compare that to the following on your platform; one branch might win against the extra modulo:

    res = n % m;
    if (res < 0)  res += m;
    

提交回复
热议问题