[Note] Modular Arithmetic
Modular Arithmetic
Why Take the Modulus
Modulus is a very important concept in programming and computer science. Its function is to calculate the remainder after dividing two numbers. Modulus can be used to limit the value to a range and reduce the need for calculation. range, which can greatly reduce the amount of calculation and time.
Basic Modular Arithmetic
Through the Congruence Theorem, you can learn the modular operations of basic addition, subtraction, and multiplication.
However, in division, we cannot find the corresponding relationship through the above method. In division, we can convert it into multiplying a certain number by its reciprocal so that we can use modular arithmetic on it. We also call it modular multiplicative inverse.
Modular Multiplicative Inverse
Fermat's Little Theorem
In Fermat's Little Theorem, we are told that assuming is an integer and is a prime number, then is a multiple of .
It can be expressed as , if is not a multiple of , it can be expressed as .
In algorithm questions, a value is usually given, and we want to find , so on both sides Multiplying is
Therefore the reciprocal of modulo p is . When is a prime number, finding is equivalent to finding .
LeetCode Usage
In LeetCode, the permutation and combination formula is used to calculate how many results there are. In order to facilitate calculation, we usually calculate and first, so how to calculate will require the application of Fermat's Little Theorem and the modular reciprocal. Usually in algorithm questions, in order to reduce the number, the modulus () is usually required. Therefore, after we calculate , we can use its value to calculate to find the reciprocal of modulo .
Code
int const MOD = 1e9 + 7;
int exp(int a, int b) {
int res = 1;
while (b > 0) {
if (b & 1)
ans = 1LL * ans * a % MOD;
a = 1LL * a * a % MOD;
b >>= 1;
}
return ans;
}
int main() {
int n = 10;
vector<int> fact (n + 1, 1), invFact(n + 1, 1);
for (int i = 1; i <= n; ++i) {
finv[i] = 1LL * finv[i - 1] * i % MOD;
invFact[i] = exp(finv[i], MOD - 2);
}
}