The modulo \(10^9 + 7\) is frequently used in competitive programming and algorithmic problems for several reasons:

  1. Prime Number: \(10^9 + 7\) is a large prime number. The properties of prime numbers help in reducing the chances of hash collisions in various hashing algorithms. It also simplifies many mathematical operations, particularly those involving modular inverses.
  2. Prevent Overflow: Using modulo \(10^9 + 7\) helps to keep numbers manageable, avoiding overflow in computations with large numbers, especially in languages like C++ where integer overflow can be a concern.
  3. Standardization: It is a common convention in competitive programming and coding contests to use \(10^9 + 7\) as the modulus to standardize solutions and make it easier to compare results.

Modular Arithmetic Operations

When working with modular arithmetic, the following operations are commonly used:

Addition

\[ (a + b) \% m = ((a \% m) + (b \% m)) \% m \]

int add(int a, int b, int mod) {
    return (a % mod + b % mod) % mod;
}

Subtraction

\[ (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;
}

Multiplication

\[ (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

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 \]