The Remainder Operator
The Remainder Operator
The remainder operator %
computes the remainder that results when one number is divided by another. Specifically, suppose m and n are of some numeric type, where n ≠ 0. We can then define a quotient q and a remainder r as the unique values such that:
- qn + r = m;
- q is an integer;
- |qn| ≤ |m|; and
- |r| < |n|.
Then m % n gives r, and we can compute q by:
(m - r) / n
Another way to think about m % n is through the following algorithm to compute it:
- Compute |m| / |n|, and remove any fractional part.
- If m and n have the same sign, let q be the above result; otherwise, let q be the negative of the above result.
- m % n is m - qn.
Examples:
- 7 % 3 = 1
- -9 % 5 = -4
- 8 % -3 = 2
- -10 % -4 = -2
- 6.4 % 1.3 = 1.2