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

Technique

Sieve of Eratosthenes / Smallest Prime Factor

Mark composites up to N in O(N log log N) (or store smallest prime factors) to list primes and factorise many numbers fast.

Learn firstMath / Number TheoryUnlocksMobius Inversion & Multiplicative Functions
0%
mastery
0/9 solved
Practise nextCounting Coprime Pairs
IdeaPracticePitfalls

Recognise it

The signal

count primes below N

  1. 1Brute force

    Trial division per number O(sqrt n).

  2. 2The observation

    Repeated trial division: each composite is marked by its prime factors once.

  3. 3Why it works

    After processing p, every composite with smallest prime p is marked.

Reach for it when

  • +factorise many numbers <= 1e7
  • +divisor counts / totients for all numbers

Not when

  • ×single huge number (trial division up to sqrt, or Pollard rho)

Practice

Next

Counting Coprime Pairs

0/9 solved
  • T-primesCodeforces1300
  • Counting Coprime PairsCSESMedium
  • Count PrimesMedium
  • Counting DivisorsCSESMedium
  • Split a Digit String into PrimesSnowflake, AmazonOAMedium
  • GCD SubsetsCSESHard
  • Coprime SubsequencesCodeforces2000
  • Two DivisorsCodeforces2000
  • SUM and REPLACECodeforces2000

Pitfalls

Misconceptions

  • !starting marking at 2p instead of pp is correct but slower; overflow of pp
Go deeper1 combinations · resources

Combinations

  • Mobius Inversion & Multiplicative Functions+Sieve of Eratosthenes / Smallest Prime Factor+Combinatorics mod p (nCr, Catalan, stars and bars)

    count pairs/subsequences with gcd 1 (or gcd exactly g), values <= 1e6

    Mobius Inversion & Multiplicative Functions:
    invert 'divisible by d' counts into 'gcd exactly 1'
    Sieve of Eratosthenes / Smallest Prime Factor:
    a linear sieve for mu (and the multiples counts)
    Combinatorics mod p (nCr, Catalan, stars and bars):
    count pairs C(c_d, 2) or subsets 2^c_d - 1 from c_d multiples

    Counting Coprime PairsGCD SubsetsCoprime Subsequences

Resources

  • Binary exponentiationcp-algorithms · article
  • Sieve of Eratosthenescp-algorithms · article
  • Modular inversecp-algorithms · article
  • DivisibilityUSACO Guide · course
  • CombinatoricsUSACO Guide · course
  • Math cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems