Here you need the mathematical definition on remainder.
Given two integer numbers m, d, we say that r is the remainder of the division of m and d if r satisfies two conditions:
- There exists another integer k such that
m == k * d + r
, and 0 <= r < d
.
For positive numbers, in C, we have m % d == r
and m / d == k
, just by following the definition above.
From the definition, it can be obtainded that 3 % 2 == 1 and 3 / 2 == 1.
Other examples:
4 / 3 == 1 and 5 / 3 == 1, in despite of 5.0/3.0 == 1.6666 (which would round to 2.0).
4 % 3 == 1 and 5 % 3 == 2.
You can trust also in the formula r = m - k * d
, which in C is written as:
m % d == m - (m / d) * d
However, in the standard C, the integer division follows the rule: round to 0
.
Thus, with negative operands C offer different results that the mathematical ones.
We would have:
(-4) / 3 == -1, (-4) % 3 == -1 (in C), but in plain maths: (-4) / 3 = -2, (-4) % 3 = 2.
In plain maths, the remainder is always nonnegative, and less than the abs(d)
.
In standard C, the remainder always has the sign of the first operand.
+-----------------------+ | m | d | / | % | +-----+-----+-----+-----+ | 4 | 3 | 1 | 1 | +-----+-----+-----+-----+ | -4 | 3 | -1 | -1 | +-----+-----+-----+-----+ | 4 | -3 | -1 | 1 | +-----+-----+-----+-----+ | -4 | -3 | 1 | -1 | +-----------------------+
Remark: This description (in the negative case) is for standard C99/C11 only. You must be carefull with your compiler version, and do some tests.