mod is the remainder of when is divided by . It is also represented by the sign . For example, 19 % 4 is 3, since 19 = 4 * 4 + 3.
In many problems, modulo is used since if the answer is very large, modulo m (for example, ) will keep the answer thus fitting it within the primitive data type.
Properties of Modular Arithmetic
Modular Multiplicative Inverse
The modular multiplicative inverse of an integer such that,
- The value of should be in the range
- The multiplicative inverse only exists if a and m are relatively prime
Example
- , . Since , 4 is the modulo inverse of 7 under 9.
- , . Since , 5 is the modulo inverse of 5 under 8.
Calculation of Modular Multiplicative Inverse
If is prime, we can use Fermat’s little theorem to calculate the modulo inverse.
Implementation: Factorial of a Large Number
int factorial(int n, int m) {
long long ans = 1;
for (int i = 2; i <= n; ++i) {
ans = (ans * (long long) i) % m;
}
return ans % m;
}