Command Palette

Search for a command to run...

← All patterns

Pattern · Bits & Math

Number Theory and Combinatorics

GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.

Time O(log n) for gcd and power · Space O(1)

Taught in Module 39: Math for Coding Interviews

Think of it like this

Knowing that a clock wraps around at 12 lets you answer "what time is it in 1000 hours?" without counting every hour.

Clues that point here

  • → "Return the answer modulo 10⁹ + 7"
  • → Divisibility, GCD, LCM
  • → Count primes
  • → Huge exponents
  • → Count arrangements (nCr)

Not this pattern when

  • ✕ The counts are small enough to simulate directly

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Number Theory and Combinatorics · template
static final long MOD = 1_000_000_007L;
long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); }
long power(long base, long exp) {            // fast exponentiation
    long result = 1; base %= MOD;
    while (exp > 0) {
        if ((exp & 1) == 1) result = result * base % MOD;
        base = base * base % MOD;
        exp >>= 1;
    }
    return result;
}

Common versions

  • Count primes (sieve)
  • Pow(x, n)
  • Unique paths via nCr
  • Modular inverse
  • Excel sheet column number

Practice problems with this pattern

Related patterns