Arrays & Hashing · Pattern 22 of 26

Math and number theory

A handful of facts solve a whole family of problems: the sieve for primes, GCD for reachability, base conversion for digits, and a counting formula instead of a loop.

5 variations · 13 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Count primes, divisors or perfect squares
  • Can you reach a value using only these moves?
  • Digits, bases, column titles, reversing numbers
  • n is huge (10⁹ or more), so the answer must be a formula

The template

Math / Number Theory
// Sieve of Eratosthenes: how many primes are < n
int countPrimes(int n) {
    if (n < 3) return 0;
    boolean[] composite = new boolean[n];
    int count = 0;
    for (int i = 2; i < n; i++) {
        if (composite[i]) continue;
        count++;
        for (long j = (long) i * i; j < n; j += i) composite[(int) j] = true;
    }
    return count;
}

int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }

The variations

  1. 1Sieve of Eratosthenes

    Cross out multiples of each prime starting at p². O(n log log n) for every prime below n.

    Worked example Count Primes Medium Read the solution
  2. 2GCD and reachability

    With jugs of a and b you can measure exactly the multiples of gcd(a, b). Working backwards with modulo turns repeated subtraction into one step.

    Now you solve
  3. 3Digits and bases

    Peel digits with % 10 and / 10; build numbers with × base + digit. Base-26 column titles have no zero, so shift by one.

  4. 4A formula instead of a loop

    Bulb i is toggled once per divisor, so only perfect squares stay on: the answer is ⌊√n⌋. Inclusion-exclusion, |a − b| expansions and clock angles are formulas too.

    Worked example Bulb Switcher Medium Read the solution
  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Starting the inner sieve loop at 2·i instead of i·i (correct but slower), or at i·i in int and overflowing.
  • Reversing an integer without checking overflow before the last multiply.
  • Column titles: there is no zero digit, so subtract 1 before each % 26.
Next: Generate a few candidates, keep the best →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.