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/Inclusion-Exclusion Principle

Technique · CP 2000

Mobius Inversion & Multiplicative Functions

Count pairs or subsets by gcd in two steps. First, for every d, count the items divisible by d (a harmonic sum, O(V log V)). Then invert: the exactly-gcd-1 count is the sum of mu(d)*f(d). A linear sieve gives mu, phi and divisor functions.

Learn firstInclusion-Exclusion PrincipleSieve of Eratosthenes / Smallest Prime FactorGCD / LCM & Euclid
0%
mastery
0/7 solved
Practise nextCounting Coprime Pairs
IdeaPracticePitfalls

Recognise it

The signal

count coprime pairs/subsequences

  1. 1Brute force

    All pairs with gcd: O(n2 log V).

  2. 2The observation

    The number of pairs.

  3. 3Why it works

    The sum of mu(d) over d | n is [n = 1]. f(d) = number of multiples of d is easy to count, and the count with gcd exactly d follows by inversion.

Reach for it when

  • +number of subsets with gcd exactly g
  • +sum of gcd(a_i, a_j) over pairs
  • +values up to 1e6 with n up to 1e5

Not when

  • ×a single condition over at most ~20 primes (plain inclusion-exclusion)

Practice

Next

Counting Coprime Pairs

0/7 solved
  • Counting Coprime PairsCSESMedium
  • Divisor AnalysisCSESMedium
  • Same GCDsCodeforces1800
  • GCD SubsetsCSESHard
  • Coprime SubsequencesCodeforces2000
  • Mocha and StarsCodeforces2200
  • Alex and a TV ShowCodeforces2500

Pitfalls

Misconceptions

  • !iterating divisors of each element (O(n sqrt V)) instead of multiples of each d (O(V log V))
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