is multiplicative, and its defining property is
That indicator is what makes the inclusion-exclusion coefficient for divisibility.
Computing it
vector<int> mu(N + 1, 0);
mu[1] = 1;
for (int i = 1; i <= N; i++)
for (int j = 2 * i; j <= N; j += i) mu[j] -= mu[i]; // O(N log N)Or with a linear sieve, :
if (!spf[i]) { primes.push_back(i); mu[i] = -1; }
for (int p : primes) {
if ((long long)i * p > N) break;
if (i % p == 0) { mu[i*p] = 0; break; } // squared factor
mu[i*p] = -mu[i];
}Möbius inversion
There is a second, more useful form for competitive programming:
The pattern that matters
Counting pairs with :
Derivation: , then swap the order of summation.
And for a general gcd value:
Divisor-block optimisation
takes only distinct values. Group the sum by blocks where it is constant:
long long ans = 0;
for (long long l = 1, r; l <= n; l = r + 1) {
r = min(n / (n / l), m / (m / l));
ans += (prefMu[r] - prefMu[l-1]) * (n / l) * (m / l);
}per query after an sieve of the prefix sums of . This divisor-block (or “整除分块”) technique is essential — it turns sums into and appears in almost every Möbius problem.
Worked problems
| Problem | Formula |
|---|---|
| Coprime pairs | |
| Pairs with | |
| (or via ) | |
| Squarefree numbers | |
| Count not divisible by any of | inclusion-exclusion, which is restricted to those primes |
| expand as , then Möbius |
Möbius vs plain inclusion-exclusion
They are the same principle. Explicit inclusion-exclusion over primes costs terms; Möbius packages exactly those signs into a single function you can sieve, so the sum runs over rather than over subsets. When the “sets” are divisibility by primes, always prefer .
Mertens function
. Computable for huge by the same recursion used for :
with divisor blocks and memoisation — after sieving small values. The same machinery (“Du’s sieve” / Dirichlet hyperbola method) computes prefix sums of , , and other multiplicative functions for up to .
See also: Euler Totient · Dirichlet Convolution · Inclusion-Exclusion