Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Math & Number Theory/Math / Number Theory

Learn the pattern · ~15 min

Math / Number Theory

also called number theory, arithmetic

When a loop over a huge range is too slow, look for the arithmetic fact that skips it: cross out multiples instead of testing divisors, halve exponents instead of multiplying n times, take the mod at every step.

Signalsanswer mod 1e9+7primes/divisors/gcdhuge n where only a formula is fast
Cheat sheet and practice

Reach for it when you read

  • +Primes up to a limit, or many "is x prime?" questions: sieve once.
  • +An answer "mod 10⁹ + 7" with a huge exponent or count: fast power, and reduce after every multiply.
  • +Digits of a number: reverse it, sum them, test a palindrome, convert a base (% 10, / 10).
  • +Divisibility, common factors or a repeating block: gcd, or count a prime inside n! (trailing zeros).
  • +Your loop runs up to n when the fact you need only needs √n or log n steps.

Not this one when

  • ×A long recurrence (Fibonacci-like) asked at n = 10¹⁸: matrix exponentiation, fast power on a matrix.
  • ×Counting subsets or arrangements with constraints: usually DP, not a closed formula.
  • ×Bit-level tricks like XOR pairs or counting 1 bits: bit manipulation.

Learn Math / Number Theory

First, what are primes, and what's a sieve?

A prime is a whole number above 1 whose only divisors are 1 and itself. 7 is prime: nothing between 2 and 6 divides it. 12 is not, because 12 = 2 × 2 × 3. A number above 1 that isn't prime is composite.

A sieve is a kitchen strainer: you pour everything in and keep only what gets through. The sieve of Eratosthenes does that with numbers. Write down 2, 3, 4, … and cross out every number that has a smaller divisor. What's never crossed out is prime.

The sieve is the math tool you'll use most; gcd and fast power come at the end.

How does the sieve work?

Take every number below 30. The rule is one line:

The smallest number that isn't crossed out yet is prime. Cross out all its multiples, then move on.

A star marks a number that was already crossed out before.

p what happens crosses out
2 not crossed, so 2 is prime 4 6 8 10 12 14 16 18 20 22 24 26 28
3 not crossed, prime 6* 9 12* 15 18* 21 24* 27
4 crossed by 2, skip
5 not crossed, prime 10* 15* 20* 25
6 crossed, skip
7 not crossed, prime 14* 21* 28*
11, 13 prime 22*, 26*
17, 19, 23, 29 prime no multiple below 30

Never crossed: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29. Notice the stars: from 7 on, every multiple is already gone. Keep that in mind.

The code for it

C++
vector<bool> plainSieve(int n) {          // composite[x] for 0 <= x < n
    vector<bool> composite(n, false);
    for (int p = 2; p < n; p++) {
        if (composite[p]) continue;         // crossed by a smaller prime
        for (int q = 2 * p; q < n; q += p)
            composite[q] = true;            // every multiple of p is not prime
    }
    return composite;
}

You don't need to memorise this. It's the table above: walk the numbers, skip crossed ones, and every uncrossed one crosses out its multiples.

Why is an uncrossed number always prime? If p had a divisor d between 2 and p − 1, then d has a prime factor smaller than p, and that prime crossed out all its multiples, p included. So reaching p uncrossed means nothing smaller divides it.

Fine, but how does this help us?

Here's the classic problem: Count Primes. Given n, how many primes are strictly less than n?

Solve n = 30 by hand the direct way: test each number by trying divisors d = 2, 3, … while d × d ≤ x. (If x = a × b with a ≤ b, then a × a ≤ x, so a divisor would show up by then.)

x divisors tried how you found it
2, 3 none (2 × 2 > x) prime
4, 6, 8, …, 28 2 divides, composite
9, 15, 21, 27 2, 3 3 divides, composite
25 2, 3, 4, 5 5 divides, composite
5, 7 2 3 × 3 > x, prime
11, 13 2, 3 prime
17, 19, 23 2, 3, 4 prime
29 2, 3, 4, 5 6 × 6 > 29, prime

That's 10 primes, so the answer is 10.

The brute force

C++
bool isPrime(int x) {
    if (x < 2) return false;
    for (long long d = 2; d * d <= x; d++)
        if (x % d == 0) return false;       // found a divisor
    return true;
}
int bruteCount(int n) {
    int count = 0;
    for (int x = 2; x < n; x++) count += isPrime(x);
    return count;
}

It's correct, but count the work. A prime x tries about √x divisors. For n = 5 × 10⁶ (Count Primes' limit) that's 654,184,149 divisions. To be fair, compiled C++ does that in about half a second, so it can pass there; in Python it's far too slow. And it grows fast: n = 5 × 10⁷ needs 17 billion divisions, about 10 seconds even in C++. The sieve below does 11 million plain writes at n = 5 × 10⁶, 58 times less work.

The one thought that fixes it

Stop at x = 25. Trial division asks 2? 3? 4? 5? Four divisions to learn one fact. And asking 4 was pointless: anything 4 divides, 2 divides too.

Flip the question. Don't ask "who divides x?" for every x. Let each prime walk over its own multiples, which costs one step per multiple and no division at all. That's the sieve. Now look back at the stars in its table:

  • Start at p². Every multiple k × p with k < p has a smaller factor k, so a smaller prime already crossed it. For p = 5, the numbers 10, 15 and 20 all had stars. The first new one is 25 = 5 × 5.
  • Stop once p² ≥ n. Every composite below n has a factor at most √n, so it's crossed by then. At p = 6, 36 ≥ 30: we're done. That's why 7, 11 and 13 only produced stars.

The code for the problem

C++
int countPrimes(int n) {
    vector<bool> composite(max(n, 2), false);
    for (long long p = 2; p * p < n; p++) {
        if (composite[p]) continue;
        for (long long q = p * p; q < n; q += p)   // start at p²: smaller multiples are done
            composite[q] = true;
    }
    int count = 0;
    for (int x = 2; x < n; x++)
        if (!composite[x]) count++;
    return count;
}

long long keeps p * p from overflowing; max(n, 2) keeps n = 0 and n = 1 safe (both return 0).

Dry run, n = 30

p what happens crosses out (* = already crossed)
2 prime, start at 4 4 6 8 10 12 14 16 18 20 22 24 26 28
3 prime, start at 9 9 12* 15 18* 21 24* 27
4 crossed, skip none
5 prime, start at 25 25
6 36 ≥ 30, the loop stops

21 cross-outs instead of 30, and 3 stars instead of 12. Never crossed: 2 3 5 7 11 13 17 19 23 29, ten numbers, the same answer as the brute force.

Why it's O(n log log n)

Count the work per prime: p crosses out about n / p cells. So the total is n × (1/2 + 1/3 + 1/5 + 1/7 + …) over the primes up to √n. That sum grows like log log n, which is barely more than a constant. For n = 5 × 10⁶ the sieve made 11,192,868 cross-outs, about 2.2 per number. Space: one bit per number, O(n).

From about n√n / log n divisions (654 million at n = 5 × 10⁶) down to about two writes per number, by letting primes find their multiples.

Greatest common divisor? Keep the remainder

gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. Anything dividing a and b also divides a % b, so the answer doesn't change, but the numbers shrink fast: gcd(84, 36) → gcd(36, 12) → gcd(12, 0) = 12.

A huge power? Square and halve

To get aᵉ, don't multiply e times. Write e in binary and square a once per bit. 3¹³: 13 = 1101, so 3¹³ = 3⁸ × 3⁴ × 3¹ = 1,594,323, after only 4 rounds.

C++
long long gcdOf(long long a, long long b) {    // not gcd: std::gcd exists
    while (b != 0) { long long r = a % b; a = b; b = r; }
    return a;
}
long long power(long long a, long long e, long long mod) {
    long long r = 1;
    a %= mod;
    while (e > 0) {
        if (e & 1) r = r * a % mod;         // this bit of e is on
        a = a * a % mod;                    // a, a², a⁴, a⁸, …
        e >>= 1;
    }
    return r;
}

Under a modulus such as 10⁹ + 7, reduce after every multiply: both factors are below 10⁹ + 7, so a product fits in long long.

Trailing zeros of n!? Count the fives

Each trailing zero is a 10 = 2 × 5, and there are always more 2s than 5s. So count the 5s: n/5 + n/25 + n/125 + …. For 100!: 20 + 4 = 24 zeros.

Factor many numbers? Store the smallest prime factor

Run the sieve, but write p into spf[q] instead of true (only if it's still empty). Then any x below n factors by dividing out spf[x] again and again (an empty spf[x] means x itself is prime): 28 → 2, 2, 7.

Remember this

  • Primes up to a limit, or many primality checks: sieve once, then answer each in O(1).
  • Inner loop from p², outer loop while p² < n; use long long for p².
  • A huge answer "mod 10⁹ + 7": reduce after every multiply, and use fast power, never a loop of multiplications.
  • Whenever a problem asks "how many primes", "is it prime, many times" or "factor every number", it's a sieve.

Practise it on Count Primes, then Pow(x, n) (fast power, with a negative exponent), Palindrome Number (digits with % 10 and / 10), Excel Sheet Column Number (base 26), Counting Divisors (the smallest-prime-factor sieve) and Exponentiation.

Watch it work, line by line

Count Primes ↗, n = 20 → 8 (2, 3, 5, 7, 11, 13, 17, 19). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Is there an arithmetic fact (a divisibility rule, a formula, an identity like a^b = (a²)^(b/2)) that answers this without walking every number?

Reach for it when

  • +answer mod 1e9+7
  • +primes/divisors/gcd
  • +huge n where only a formula is fast
  • +digits of a number
  • +n up to 1e18 -> O(log n) or O(sqrt n)

It fails when

  • ×No identity appliesuse DP or search

Looks like it, isn't (and the other way round)

  • Happy Number looks like Math / Number Theory, needs Fast & Slow Pointers

    The question is whether an iterated function cycles; Floyd detects it without a set.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why does the sieve start crossing at p × p?Reveal

    Every smaller multiple k·p (k < p) has a prime factor smaller than p, so it's already crossed.

  • 2Why can the outer loop stop when p × p ≥ n?Reveal

    Every composite below n has a prime factor ≤ √n, so it's been crossed by then.

  • 3Where does the mod go in a long product?Reveal

    After every multiplication, with both operands already reduced and the product in 64-bit. Not once at the end.

Practice ladder

every problem →
  1. 1Palindrome Numberdigit loopsEasy
  2. 2Excel Sheet Column Numberbase conversionEasy
  3. 3Count Primesthe hookMedium
  4. 4Pow(x, n)fast powerMedium
  5. 5Trailing Zeroscount a prime factorEasy
  6. 6Counting Divisorssieve variantMedium
  7. 7Binomial Coefficientscounting under a modMedium
  8. 8Prime Multiplesinclusion–exclusionMedium

Finished Math / Number Theory? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Math / Number Theory

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial