Typically, modulo operations (MoD) and remainder (REM) operations are confused, because in most programming languages, the '% ' notation is used to represent modulo or remainder operations. Here we want to remind you to pay attention to the specific meaning of the '% ' operator in the current environment, because in the case of negative numbers, the results are different.
For integer number A,b, the method of modulo operation or remainder operation is:
1. Find the integer quotient: c = A/b;
2. Computational model or remainder: R = a-c*b.
The modulo and remainder operations are different in the first step : Modulus- seeking operations are rounded to the 0 direction (fix () function) when the value of C is taken , and the remainder modulo operation rounds in an infinitesimal direction when calculating the value of C (floor ()).
For example: The remainder is -3/4 the result is c=0, but when taken: -3/4 The result is: C=-1
Therefore, when a and B are identical, the values of the C of the modulo operation and the remainder operation are consistent, so the results are consistent. But when the symbols are inconsistent, the results are different.
In particular, the symbol of the result of the remainder operation is consistent with a, and the symbol of the result of the modulo operation is consistent with B.
In the C language, the% symbol represents the remainder operation, and in the Python script,% is the modulo. (usually b in modulo operations is not allowed to be negative, but in Python 2.5.1 It can be followed by a negative number, because the result of division in the Python language is rounding to 0, so the result is modulo.) )
The following table is a typical modulo or remainder value.
A
|
B
|
C Language: a%b (remainder)
|
Python shell:a%b (modulo)
|
-3 |
-5 |
-3 |
-3 |
-3 |
4 |
-3 |
1 |
-3 |
2 |
-1 |
1 |
-1 |
6 |
-1 |
5 |
-4 |
-3 |
-1 |
-1 |
2 |
4 |
2 |
2 |
5 |
3 |
2 |
2 |
4 |
-7 |
4 |
-3 |
4 |
-3 |
1 |
-2 |
-6 |
-5 |
-1 |
-1 |