Intuition, Vocabulary and Foundations
A gcd condition couples several values, which makes direct counting awkward. Möbius inversion replaces that global condition with a signed sum of simpler divisibility conditions. Instead of asking whether two values have gcd $1$, count how many are divisible by each $d$, then combine those counts with the Möbius function.
The central identity is
$$ \mathbf 1_{\gcd(x_1,\ldots,x_k)=1} = \sum_{d\mid\gcd(x_1,\ldots,x_k)}\mu(d). $$
The divisor sum equals $1$ when the gcd is $1$ and $0$ otherwise because $\sum_{d\mid n}\mu(d)=\mathbf1_{n=1}$. This cancellation resembles inclusion–exclusion over prime divisors. Terms with $\mu(d)=1$ add, terms with $\mu(d)=-1$ subtract, and terms with $\mu(d)=0$ ignore divisors containing a squared prime.
For a multiset of positive integers, let $C_d=\#\{i:d\mid a_i\}$. There are $\binom{C_d}{2}$ unordered index pairs whose values are both divisible by $d$. Thus the number of unordered coprime index pairs is $\sum_{d\ge1}\mu(d)\binom{C_d}{2}$. For ordered $k$-tuples from $\{1,\ldots,n\}$ with repetition, the corresponding count is $\sum_{d=1}^{n}\mu(d)\lfloor n/d\rfloor^k$. The combinatorial model determines the inner count.
Möbius inversion works because $\sum_{d\mid g}\mu(d)$ is an exact indicator for $g=1$. Before implementing the sum, define whether objects are indices or values, ordered or unordered, and chosen with or without repetition.
| Concept | Definition or identity | Concrete example | Non-example or boundary | Question answered |
|---|---|---|---|---|
| Möbius function | $μ(n)=0$ for a squared prime factor; otherwise $(-1)^r$ for $r$ distinct primes | $μ(30)=-1$, $μ(12)=0$ | It is not parity of the integer | What sign does divisor $n$ contribute? |
| Cancellation identity | $\sum_{d\mid n}\mu(d)=\mathbf1_{n=1}$ | For $n=6$, the signed divisor sum is $0$ | Summing over nondivisors breaks the identity | How is gcd equality converted to a divisor sum? |
| Divisor frequency | $C_d$ counts inputs divisible by $d$ | In $[2,3,4,6]$, $C_2=3$ | It does not count gcd exactly $d$ | How many objects satisfy one divisibility condition? |
| Unordered pair count | $\binom{C_d}{2}$ | Three divisible entries create three pairs | $C_d^2$ counts a different model | Which count matches distinct unordered indices? |
| Ordered tuple count | $\lfloor n/d\rfloor^k$ | Multiples of $d$ fill all $k$ positions | Repeated values are allowed | How many tuples are coordinatewise divisible by $d$? |
| Exact gcd count | Scale by the target gcd or invert divisor totals | Count gcd $g$ through multiples of $g$ | Coprime counting alone isolates only $1$ | How is a specified gcd isolated? |
| Mertens prefix | $M(x)=\sum_{d\le x}\mu(d)$ | Supplies block sums of $\mu$ | It is not the point value $\mu(x)$ | How are quotient-equal ranges aggregated? |
| Quotient grouping | $\lfloor n/d\rfloor$ is constant on an interval | A block ends at $\lfloor n/q\rfloor$ | Advancing one divisor at a time misses the speedup | How can the sum use $O(\sqrt n)$ blocks? |
Step-by-Step Derivations and Algorithms
For an unordered index pair $(i,j)$, insert the indicator identity:
$$ \mathbf1_{\gcd(a_i,a_j)=1} = \sum_{d\mid a_i,\ d\mid a_j}\mu(d). $$
Summing over pairs and exchanging sums gives
$$ \sum_{i\lt j}\mathbf1_{\gcd(a_i,a_j)=1} = \sum_{d\ge1}\mu(d) \sum_{\substack{i\lt j\\d\mid a_i,\ d\mid a_j}}1 = \sum_{d\ge1}\mu(d)\binom{C_d}{2}. $$
Every pair with gcd $g$ receives total weight $\sum_{d\mid g}\mu(d)$, which is one only for $g=1$. To compute all $C_d$ for values bounded by $V$, build an occurrence array and sum over multiples. The number of visits is $\sum_{d=1}^{V}\lfloor V/d\rfloor=O(V\log V)$.
For $\sum_{d\le n}\mu(d)\lfloor n/d\rfloor^k$, precompute the Mertens prefix. If $q=\lfloor n/l\rfloor$, the quotient remains constant through $r=\lfloor n/q\rfloor$, and the block contributes $(M(r)-M(l-1))q^k$. Only $O(\sqrt n)$ distinct quotients occur.
To count gcd exactly $g$, divide eligible values by $g$ and count coprime objects in the scaled domain, or recover all exact-gcd counts by descending divisor inversion. The best approach depends on whether there is one target or an entire gcd distribution.
flowchart TD
A["Define ordered or unordered objects"] --> B["Replace gcd condition by divisor indicator"]
B --> C{"Explicit multiset?"}
C -->|Yes| D["Build value frequencies"]
D --> E["Accumulate counts over multiples"]
E --> F["Apply mu[d] times combinatorial count"]
C -->|No, dense interval| G["Precompute mu and Mertens prefix"]
G --> H{"Repeated floor quotients?"}
H -->|Yes| I["Group quotient intervals"]
H -->|No| J["Sum directly"]
F --> K["Verify against gcd oracle"]
I --> K
J --> K
For each object with gcd $g$, the algorithm assigns total weight $\sum_{d\mid g}\mu(d)=\mathbf1_{g=1}$, proving exactness. Divisor-frequency preprocessing costs $O(V\log V)$ time and $O(V)$ space for maximum value $V$; after Möbius-prefix preprocessing, a dense floor-quotient sum uses $O(\sqrt n)$ blocks.
Implementation, Complexity and Engineering
The reference implementation computes $\mu$ with a linear sieve, counts unordered coprime index pairs in a positive-integer multiset, and counts ordered coprime tuples from a dense interval. Independent brute-force functions verify both counting models.
Python integers prevent count overflow. In fixed-width languages, $\binom{C_d}{2}$ may require 64 bits even when values use 32 bits, and $\lfloor n/d\rfloor^k$ grows rapidly. Use checked wide arithmetic or reduce modulo a specified output modulus.
| Implementation choice | Counting model | Complexity | Numeric risk | Failure mode | Mitigation |
|---|---|---|---|---|---|
| Pairwise gcd scan | Unordered index pairs | $O(N^2\log V)$ | Pair count may exceed 32 bits | Too slow for large $N$ | Keep as a small oracle |
| Divisor-frequency inversion | Unordered index pairs | $O(V\log V+N)$ | $\binom N2$ needs a wide type | Losing multiplicities | Build frequencies by index multiplicity |
| Ordered pair formula | Model-dependent | Similar preprocessing | Count near $N^2$ | Reusing the unordered formula | Derive from the object definition |
| Dense tuple sum | Ordered tuples with repetition | $O(n)$ direct after sieve | $n^k$ grows quickly | Assuming values are distinct | State repetition semantics |
| Quotient grouping | Same dense model | $O(\sqrt n)$ after prefix data | Powers may overflow | Wrong block endpoint | Use the quotient endpoint formula |
| Linear Möbius sieve | Prefix of $\mu$ | $O(V)$ time and space | Memory proportional to $V$ | Missing repeated-prime break | Test the whole prefix |
| Modular output | Counts modulo a target | Same asymptotic work | Negative signed terms | Returning negative residues | Normalize after accumulation |
| Sparse large values | Huge maximum value | Domain-dependent | Dense memory exhaustion | Allocating through the maximum | Factor distinct values and map divisors sparsely |
Applications, Case Studies and Exercises
Möbius inversion appears whenever common-divisor counts are easy but exact gcd constraints are hard. Typical uses include coprime array pairs, primitive lattice points, visible grid directions, tuples with gcd one, and full gcd histograms.
Apply Möbius Inversion for Coprime Counting
Case study 1 — count coprime pairs. Use [2, 3, 4, 6]. Compute $C_1=4$, $C_2=3$, $C_3=2$, and the remaining relevant frequencies. Evaluate $\sum_d\mu(d)\binom{C_d}{2}$ and list the two coprime index pairs directly. Success means both methods return 2 and every noncoprime pair cancels.
Case study 2 — process telemetry periods. For millions of positive periods bounded by $10^6$, build frequency and Möbius tables and count unordered coprime device pairs. Duplicates represent distinct devices. Record memory, preprocessing time, maximum intermediate count, and compare small prefixes with a gcd oracle. Success means multiplicities and numeric widths are correct.
Hands-on quotient grouping. For $k=2$ and $k=3$, count ordered tuples in $[1,n]^k$ with gcd one. Compare direct Möbius summation, quotient grouping, and brute force for every $n\le30$. For $n=10^6$, report the block count. Success means exact agreement and explicit order-and-repetition semantics.
Tiered exercises. Recall: state Möbius cancellation. Derive: exchange the pair and divisor sums. Implement: count pairs with gcd exactly $g$. Debug: find the factor-of-two error from using $C_d(C_d-1)$. Extend: compute the full pair-gcd histogram by descending divisor inversion.
Use Möbius inversion when common-divisor counts are easy but exact gcd constraints are hard; use direct gcd enumeration for tiny inputs and as an oracle. Always define ordering, repetition, multiplicity, positivity, maximum-value feasibility, and numeric width before selecting the inner combinatorial count.