9 mod 5
14 mod 12
9 + 5
12 mod 5
a mod n = r
The Remainder
The Congruence
The Dividend
The Modulus
25 % 7
5
4
3.57
3
/
%
13 / 5
13 % 5
Both operators give the same result.
/ gives the remainder, % gives the quotient.
/ gives a floating-point result, % gives an integer.
/ gives the quotient, % gives the remainder.
8 + 4
(8 + 4) / 10
(8 % 10) + 4
(8 + 4) % 10
(a+b)%n=((a%n)+(b%n))%n(a + b) \% n = ((a \% n) + (b \% n)) \% n(a+b)%n=((a%n)+(b%n))%n
(a+b)%n=(a%n)+(b%n)(a + b) \% n = (a \% n) + (b \% n)(a+b)%n=(a%n)+(b%n)
(a+b)%n=(a+n)%(b+n)(a + b) \% n = (a + n) \% (b + n)(a+b)%n=(a+n)%(b+n)
(a+b)%n=a%n+b(a + b) \% n = a \% n + b(a+b)%n=a%n+b
(a + b) % n = ((a % n) + (b % n)) % n
int
It makes the code run faster.
It is the only way to perform addition in C++.
It helps prevent integer overflow when a and b are very large numbers.
a
b
It simplifies debugging by making numbers smaller.
(-5 % 12)
Take the absolute value: abs(-5)
abs(-5)
Add the modulus: (-5 % 12) + 12
(-5 % 12) + 12
Multiply by -1: (-5 % 12) * -1
(-5 % 12) * -1
It is not possible to normalize this result.
(15 * 10) % 7
1
150
21
Sort the elements in the table.
Check if the table is full.
Map a large key value to a smaller, valid array index.
Encrypt the data being stored.
'C'
The operation is invalid because it goes past 'Z'.
'B'
'Z'
(a * b) % n
a * b
It produces a negative result.
It can cause a division-by-zero error.
It is much slower than applying the modulus at each step.
The intermediate product a * b might cause an integer overflow, leading to an incorrect final result.
n
False
True
(100 - 55) % 9
45
0
int sub(int a, int b, int m) { int res = (a % m - b % m); if (res < 0) res += m; return res; }
int sub(int a, int b, int m) { return (a % m) - (b % m); }
int sub(int a, int b, int m) { return abs(a - b) % m; }
int sub(int a, int b, int m) { return (a - b) % m; }
All done? Get your grade