How to get the remainder of an integer division operation?
Answer 1, authority 100%
very simple
if (x% t! = 0) {
cout & lt; & lt; "when dividing x by t, there is a remainder" & lt; & lt; endl;
} else {
cout & lt; & lt; "no remainder" & lt; & lt; endl;
}
Answer 2, authority 25%
WITHmath point view , the operation of calculating the remainder in C / C++ for negative numbers, for example -11% 8 == -3
, does not give the result that we are used to from school. Of course, this is a matter of agreement , but …
This problem sometimes causes confusion and heated debate .
If the task is to determine only the absence of the remainder, then %
is sufficient. However, there is a particular solution when the divisor is a number of power 2. The same method is the simplest for determining the remainder of a division by numbers greater than 1 equal to power 2.
int a;
int b; // 2 to the power n
if (a & amp; (b - 1))
// remainder from division is present. For example, -11 & amp; (8 - 1) == 5
else
// remainder is zero. For example -8 & amp; (8 - 1) == 0
Why is this important? Consider the sequence mod (n, 4)
For n & amp; (4-1) the sequence is periodic
n -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
n & amp; 3 3 * * * *
2 * * * *
1 * * * *
0 * * * * *
For n% 4, the sequence is generally non-periodic
n -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8
n% 4 3 * *
2 * *
1 * *
0 * * * * *
-1 * *
-2 * *
-3 * *
Working with a periodic sequence is much more pleasant where it is required to maintain equal intervals between events. You can build a construction like
switch (i & amp; 3) {
case 0: / * event 1 * /; break;
case 1: / * event 2 * /; break;
case 2: / * event 3 * /; break;
case 3: / * event 4 * /; break;
}
and be sure that each event will occur with enviable regularity regardless of the i
sign and no additional case
is required.