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

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

    How about

    if (a > 0)
        return a % n;
    if (a < 0)
    {
        r = n - (-a % n);
        if (r == n)
            return 0;
        return r;
    }
    

    If a < 0, then r = -a % n is a value in [0, n) such that k * n + r = -a for some integer k. Then n - r is a value in (0, n], and since -r = a + k * n, we have n - r = a + (k + 1) * n, or a = (n - r) + (-k - 1) * n. From this you can see that n - r is the modulus of a, and since it is in (0, n], it is non-negative.

    Finally, you want the result to be in the range [0, n), not in (0, n]. To ensure this, we check if r is n, and if so, return 0. (Which is of course modulus-n-equivalent to n)

提交回复
热议问题