🔒 Private Site

This site is password-protected.


title: Math & Number Theory —

Math & Number Theory

Math and number theory topics are frequently used in competitive programming for problems involving primes, divisibility, and modular arithmetic.

Applications

1. The Building Blocks: Primality & Divisibility

A number $n$ is prime if its only divisors are $1$ and $n$ itself. To check this efficiently:

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true; // Ensures the function returns true if no divisors are found
}

2. Greatest Common Divisor (GCD)

The GCD (Greatest Common Divisor) of two numbers $a$ and $b$ is the largest number that divides both $a$ and $b$.

On Codeforces, you will often see problems asking for the GCD of an array.

\[\gcd(a, b) = \gcd(b,\ a \bmod\ b)\]

3. Modular Arithmetic (The “Remainder” Math)

Most Codeforces problems ask you to output the answer “modulo $10^9 + 7$”. This is because the actual answer is too large to fit in a long long.

Some important modular arithmetic properties:

\[(a + b) \bmod m = \left[(a \bmod m) + (b \bmod m)\right] \bmod m\] \[(a \times b) \bmod m = \left[(a \bmod m) \times (b \bmod m)\right] \bmod m\]

Important: Always use long long when multiplying before taking the modulo to avoid overflow!

Practice Problems

LeetCode
204. Count Primes
Solution | Approach
Codeforces
230B. T-primes
Solution | Approach
Codeforces
1328A. Divisibility Problem
Solution | Approach
Codeforces
1370A. Maximum GCD:
Solution | Approach
Codeforces
1594A. Consecutive Sum Riddle
Solution | Approach