The modulo \(10^9 + 7\) is frequently used in competitive programming and algorithmic problems for several reasons:
When working with modular arithmetic, the following operations are commonly used:
\[ (a + b) \% m = ((a \% m) + (b \% m)) \% m \]
int add(int a, int b, int mod) {
return (a % mod + b % mod) % mod;
}
\[ (a - b) \% m = ((a \% m) - (b \% m) + m) % m \]
Adding m
before taking the modulus ensures that the result is non-negative.
int subtract(int a, int b, int mod) {
return ((a % mod - b % mod) + mod) % mod;
}
\[ (a \times b) \% m = ((a \% m) \times (b \% m)) \% m \]
int multiply(int a, int b, int mod) {
return (1LL * (a % mod) * (b % mod)) % mod;
}
Note: The 1LL *
is used to prevent overflow by promoting the multiplication to a long long
.
Division under modulo requires the concept of modular multiplicative inverse. For a number b
modulo m
, the modular inverse is a number b_inv
such that:
\[ (b \times b\_inv) \% m = 1 \]