Möbius Inversion

Prerequisites: number-theoretic block decomposition, Dirichlet convolution

Möbius inversion is an important topic in number theory. For some functions f(n)f(n), if it is difficult to compute their values directly but easy to compute their multiple sums or divisor sums g(n)g(n), Möbius inversion can simplify the computation and yield the values of f(n)f(n).

Möbius Function

The Möbius function is defined by

μ(n)={1,n=1,0,n is divisible by a square >1,(−1)k,n is the product of k distinct primes.\mu(n)= \begin{cases} 1,&n=1,\\ 0,&n\text{ is divisible by a square }>1,\\ (-1)^k,&n\text{ is the product of }k\text{ distinct primes}.\\ \end{cases}

Specifically, suppose the positive integer nn has prime factorization n=∏i=1kpiein=\prod_{i=1}^kp_i^{e_i}, where pip_i are primes and eie_i are positive integers. The three cases correspond to:

  1. μ(1)=1\mu(1) = 1;
  2. If there exists ii with ei>1e_i > 1, meaning that some prime factor occurs more than once, then μ(n)=0\mu(n)=0;
  3. Otherwise, for every ii, ei=1e_i = 1, meaning every prime factor occurs exactly once, μ(n)=(−1)k\mu(n)=(-1)^k, where kk is the number of distinct prime factors.

Properties

It is easy to verify from the definition that the Möbius function μ(n)\mu(n) is multiplicative but not completely multiplicative. More importantly, it satisfies the following identity:

Property

For a positive integer nn,

∑d∣nμ(d)=[n=1]={1,n=1,0,n≠1.\sum_{d\mid n}\mu(d) = [n = 1] = \begin{cases} 1,&n=1,\\ 0,&n\neq 1.\\ \end{cases}

Here [⋅][\cdot] is the Iverson bracket.

Proof

Let n=∏i=1kpiein=\prod_{i=1}^kp_i^{e_i} and let n′=∏i=1kpin' = \prod_{i=1}^kp_i. By the binomial theorem,

∑d∣nμ(d)=∑d∣n′μ(d)=∑i=0k(ki)(−1)i=(1+(−1))k=[k=0]=[n=1].\sum_{d\mid n}\mu(d) = \sum_{d\mid n'}\mu(d) = \sum_{i=0}^k\binom{k}{i}(-1)^i = (1 + (-1))^k = [k = 0] = [n = 1].

Using Dirichlet convolution, this expression can be written as ε=1∗μ\varepsilon = 1 * \mu. In other words, the Möbius function is the Dirichlet inverse of the constant function 11.

A very common application of this property is:

[i⊥j]=[gcd⁡(i,j)=1]=∑d∣gcd⁡(i,j)μ(d)=∑d[d∣i][d∣j]μ(d).[i\perp j] = [\gcd(i,j) = 1] = \sum_{d\mid\gcd(i,j)} \mu(d) = \sum_{d}[d\mid i][d\mid j]\mu(d).

This converts the coprimality condition into a sum involving the Möbius function, making further derivations convenient.

Computing the Function

For a single nn, compute the value μ(n)\mu(n) of the Möbius function using its prime factorization. For example, when nn is not too large, it can be computed in O(n)O(\sqrt{n}) time, yielding μ(n)\mu(n).

Reference Implementation

C++

int mu(int n) {
  int res = 1;
  for (int i = 2; i * i <= n; ++i) {
    if (n % i == 0) {
      n /= i;
      // Check if square-free.
      if (n % i == 0) return 0;
      res = -res;
    }
  }
  // The remaining factor must be prime.
  if (n > 1) res = -res;
  return res;
}

Python

def mu(n):
    res = 1
    i = 2
    while i * i <= n:
        if n % i == 0:
            n //= i
            # Check if square-free
            if n % i == 0:
                return 0
            res = -res
        i += 1
    # The remaining factor must be prime
    if n > 1:
        res = -res
    return res

For the first nn positive integers, precompute μ(n)\mu(n) using its multiplicativity and a linear sieve in O(n)O(n) time.

Reference Implementation

C++

std::vector<int> get_mu(int n) {
  std::vector<int> mu(n + 1), primes;
  std::vector<bool> not_prime(n + 1);
  primes.reserve(n);
  mu[1] = 1;
  for (int x = 2; x <= n; ++x) {
    if (!not_prime[x]) {
      primes.push_back(x);
      mu[x] = -1;
    }
    for (int p : primes) {
      if (x * p > n) break;
      not_prime[x * p] = true;
      if (x % p == 0) {
        mu[x * p] = 0;
        break;
      } else {
        mu[x * p] = -mu[x];
      }
    }
  }
  return mu;
}

Python

def get_mu(n):
    mu = [0] * (n + 1)
    primes = []
    not_prime = [False] * (n + 1)

    mu[1] = 1
    for x in range(2, n + 1):
        if not not_prime[x]:
            primes.append(x)
            mu[x] = -1
        for p in primes:
            if x * p > n:
                break
            not_prime[x * p] = True
            if x % p == 0:
                mu[x * p] = 0
                break
            else:
                mu[x * p] = -mu[x]
    return mu

Möbius Inversion

The most important application of the Möbius function is Möbius inversion.

Möbius Inversion

Let f(n),g(n)f(n),g(n) be two arithmetic functions. Then

f(n)=∑d∣ng(d)  ⟺  g(n)=∑d∣nμ(nd)f(d).f(n) = \sum_{d\mid n}g(d) \iff g(n) = \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)f(d).
Proof 1

Direct verification gives:

∑d∣nμ(nd)f(d)=∑d∣nμ(nd)∑k∣dg(k)=∑k∣ng(k)∑d[k∣d∣n]μ(nd)=∑k∣ng(k)∑d∣n[nd∣nk]μ(nd)=∑k∣ng(k)[nk=1]=g(n).\begin{aligned} \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)f(d) &= \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)\sum_{k\mid d}g(k)\\ &= \sum_{k\mid n}g(k)\sum_d[k\mid d\mid n]\mu\left(\dfrac{n}{d}\right)\\ &= \sum_{k\mid n}g(k)\sum_{d\mid n}\left[\frac{n}{d}\mid\frac{n}{k}\right]\mu\left(\dfrac{n}{d}\right)\\ &= \sum_{k\mid n}g(k)\left[\frac{n}{k} = 1\right] \\ &= g(n). \end{aligned}

The key steps are exchanging the order of summation and observing that k∣d∣nk\mid d\mid n is equivalent to nd∣nk\dfrac{n}{d}\mid\dfrac{n}{k}. The penultimate equality sums the Möbius function over the divisors nk\dfrac{n}{k} of nd\dfrac{n}{d}, so it equals [nk=1]\left[\dfrac{n}{k} = 1\right]. This expression is nonzero only when n=kn=k; in that case, it is not 00, and the result is g(n)g(n).

Proof 2

Using Dirichlet convolution, the proposition is equivalent to

f=1∗g  ⟺  g=μ∗f.f = 1 * g \iff g = \mu * f.

Using 1∗μ=ε1 * \mu = \varepsilon, convolve both sides of the equality on the left with μ\mu; this gives

f∗μ=(1∗g)∗μ=(1∗μ)∗g=ε∗g=g.f * \mu = (1 * g) * \mu = (1 * \mu) * g = \varepsilon * g = g.

Möbius inversion is a powerful transformation tool for sums of arithmetic functions involving divisibility relations.

Examples
  1. The Euler totient function φ(n)\varphi(n) satisfies n=∑d∣nφ(d)n = \sum_{d\mid n}\varphi(d), equivalently id=1∗φ\mathrm{id}=1*\varphi. Inverting it gives φ=μ∗id\varphi = \mu * \mathrm{id}, equivalently

    φ(n)=∑d∣ndμ(nd).\varphi(n) = \sum_{d\mid n}d\mu\left(\dfrac{n}{d}\right).
  2. The divisor function σk(n)=∑d∣ndk\sigma_k(n) = \sum_{d\mid n}d^k, equivalently σk=1∗idk\sigma_k = 1 * \mathrm{id}_k. Inverting it gives idk=μ∗σk\mathrm{id}_k = \mu * \sigma_k, equivalently

    nk=∑d∣nμ(nd)σk(d).n^k = \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)\sigma_k(d).
  3. The number of distinct prime factors ω(n)=∑d∣n[d∈P]\omega(n)=\sum_{d\mid n}[d\in\mathbf P], equivalently ω=1∗1P\omega = 1* \mathbf{1}_{\mathbf P}, where 1P\mathbf{1}_{\mathbf P} is the indicator of the prime set P\mathbf P. Inverting it gives 1P=μ∗ω\mathbf{1}_{\mathbf P} = \mu * \omega, equivalently

    [n∈P]=∑d∣nμ(nd)ω(d).[n\in\mathbf P] = \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)\omega(d).
  4. Consider the arithmetic function satisfying log⁡n=∑d∣nΛ(d)\log n = \sum_{d\mid n}\Lambda(d), denoted by Λ(n)\Lambda(n). It is the Möbius inversion of the logarithm and is also called the von Mangoldt function:

    Λ(n)=∑d∣nμ(nd)log⁡d={log⁡p,n=pe, p∈P, e∈N+,0,otherwise.\Lambda(n) = \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)\log d = \begin{cases} \log p, & n = p^e,~p\in\mathbf P,~e\in\mathbf N_+, \\ 0, &\text{otherwise}. \end{cases}
Proof of the expression for Λ(n)\Lambda(n)

For a prime power n=pe (e∈N+)n=p^e~(e\in\mathbf N_+), there is

Λ(n)=∑i=0eμ(pe−i)log⁡pi=log⁡pe−log⁡pe−1=log⁡p.\Lambda(n) = \sum_{i=0}^e\mu(p^{e-i})\log p^i = \log p^{e} - \log p^{e-1} = \log p.

For n=1n=1, clearly Λ(n)=log⁡1=0\Lambda(n)=\log 1=0. For other composite nn,

Λ(n)=∑d∣nμ(d)(log⁡n−log⁡d)=(∑d∣nμ(d))log⁡n−∑d∣nμ(d)log⁡d.\Lambda(n) = \sum_{d\mid n}\mu(d)(\log n-\log d) = \left(\sum_{d\mid n}\mu(d)\right)\log n-\sum_{d\mid n}\mu(d)\log d.

By the properties of the Möbius function, the coefficient of the term log⁡n\log n is [n=1]=0[n=1]=0. For the latter term, factor dd further into primes. For any prime p∣np\mid n, consider the coefficient of log⁡p\log p; it is:

−∑p∣d∣nμ(d)=∑(d/p)∣(n/p)μ(dp)=[np=1]=0.-\sum_{p\mid d\mid n}\mu(d) = \sum_{(d/p)\mid(n/p)}\mu\left(\dfrac{d}{p}\right) = \left[\dfrac{n}{p}=1\right]=0.

Thus every composite nn with more than one prime factor satisfies Λ(n)=0\Lambda(n)=0.

Extensions

Besides the basic form above, Möbius inversion has several common extensions. First consider its multiple-sum form.

Extension 1

Let f(n),g(n)f(n),g(n) be two arithmetic functions. Then

f(n)=∑n∣dg(d)  ⟺  g(n)=∑n∣dμ(dn)f(d).f(n) = \sum_{n\mid d}g(d) \iff g(n) = \sum_{n\mid d}\mu\left(\dfrac{d}{n}\right)f(d).
Proof

Direct verification gives:

∑n∣dμ(dn)f(d)=∑n∣dμ(dn)∑d∣kg(k)=∑n∣kg(k)∑d[n∣d∣k]μ(dn)=∑n∣kg(k)∑n∣d[dn∣kn]μ(dn)=∑n∣kg(k)[kn=1]=g(n).\begin{aligned} \sum_{n\mid d}\mu\left(\dfrac{d}{n}\right)f(d) &= \sum_{n\mid d}\mu\left(\dfrac{d}{n}\right)\sum_{d\mid k}g(k)\\ &= \sum_{n\mid k}g(k)\sum_{d}[n\mid d\mid k]\mu\left(\dfrac{d}{n}\right)\\ &= \sum_{n\mid k}g(k)\sum_{n\mid d}\left[\dfrac{d}{n}\mid\dfrac{k}{n}\right]\mu\left(\dfrac{d}{n}\right)\\ &= \sum_{n\mid k}g(k)\left[\dfrac{k}{n}=1\right]\\ &= g(n). \end{aligned}

This derivation is completely dual to that of the basic form.

Möbius inversion is not limited to addition; in fact, it holds for operations in any Abelian group. For example, it has the following multiplicative form:

Extension 2

Let f(n),g(n)f(n),g(n) be two arithmetic functions. Then

f(n)=∏d∣ng(d)  ⟺  g(n)=∏d∣nf(d)μ(n/d).f(n) = \prod_{d\mid n}g(d) \iff g(n) = \prod_{d\mid n}f(d)^{\mu(n/d)}.
Proof

Direct verification gives:

∏d∣nf(d)μ(n/d)=∏d∣n(∏k∣dg(k))μ(n/d)=∏k∣ng(k)↑(∑d[k∣d∣n]μ(nd))=∏k∣ng(k)↑(∑d∣n[nd∣nk]μ(nd))=∏k∣ng(k)↑[nk=1]=g(n).\begin{aligned} \prod_{d\mid n}f(d)^{\mu(n/d)} &= \prod_{d\mid n}\left(\prod_{k\mid d}g(k)\right)^{\mu(n/d)}\\ &= \prod_{k\mid n}g(k)\uparrow\left(\sum_d[k\mid d\mid n]\mu\left(\dfrac{n}{d}\right)\right)\\ &= \prod_{k\mid n}g(k)\uparrow\left(\sum_{d\mid n}\left[\frac{n}{d}\mid\frac{n}{k}\right]\mu\left(\dfrac{n}{d}\right)\right)\\ &= \prod_{k\mid n}g(k)\uparrow\left[\frac{n}{k} = 1\right] \\ &= g(n). \end{aligned}

Here a↑b=aba\uparrow b = a^b is the Knuth arrow. Comparing this proof with the basic one, the only differences are replacing addition by multiplication and multiplication by exponentiation.

From the perspective of Dirichlet convolution, Möbius inversion uses only the fact that the Möbius function is the Dirichlet inverse of the constant function. It is natural that analogous inversion relations also hold for a general Dirichlet inverse.

Extension 3

Let f(n),g(n),α(n)f(n),g(n),\alpha(n) be arithmetic functions, and suppose α−1(n)\alpha^{-1}(n) is the Dirichlet inverse of α(n)\alpha(n), namely

[n=1]=∑d∣nα(nd)α−1(d).[n=1] = \sum_{d\mid n}\alpha\left(\dfrac{n}{d}\right)\alpha^{-1}(d).

Then

f(n)=∑d∣nα(nd)g(d)  ⟺  g(n)=∑d∣nα−1(nd)f(d).f(n) = \sum_{d\mid n}\alpha\left(\dfrac{n}{d}\right)g(d) \iff g(n) = \sum_{d\mid n}\alpha^{-1}\left(\dfrac{n}{d}\right)f(d).
Proof

Direct verification gives:

∑d∣nα−1(nd)f(d)=∑d∣nα−1(nd)∑k∣dα(dk)g(k)=∑k∣ng(k)∑d[k∣d∣n]α(dk)α−1(nd)=∑k∣ng(k)∑d∣n[nd∣nk]α(dk)α−1(n/kd/k)=∑k∣ng(k)[nk=1]=g(n).\begin{aligned} \sum_{d\mid n}\alpha^{-1}\left(\dfrac{n}{d}\right)f(d) &= \sum_{d\mid n}\alpha^{-1}\left(\dfrac{n}{d}\right)\sum_{k\mid d}\alpha\left(\dfrac{d}{k}\right)g(k)\\ &= \sum_{k\mid n}g(k)\sum_d[k\mid d\mid n]\alpha\left(\dfrac{d}{k}\right)\alpha^{-1}\left(\dfrac{n}{d}\right)\\ &= \sum_{k\mid n}g(k)\sum_{d\mid n}\left[\frac{n}{d}\mid\frac{n}{k}\right]\alpha\left(\dfrac{d}{k}\right)\alpha^{-1}\left(\dfrac{n/k}{d/k}\right)\\ &= \sum_{k\mid n}g(k)\left[\frac{n}{k} = 1\right] \\ &= g(n). \end{aligned}

Compared with the proof of the basic form, only the penultimate equality needs to be replaced by the definition of the Dirichlet inverse.

Corollary

Let f(n),g(n)f(n),g(n) be arithmetic functions, and let t(n)t(n) be completely multiplicative. Then

f(n)=∑d∣nt(nd)g(d)  ⟺  g(n)=∑d∣nμ(nd)t(nd)f(d).f(n) = \sum_{d\mid n}t\left(\dfrac{n}{d}\right)g(d) \iff g(n) = \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)t\left(\dfrac{n}{d}\right)f(d).
Proof

By the properties of Dirichlet convolution, the Dirichlet inverse of a completely multiplicative function t(n)t(n) is μ(n)t(n)\mu(n)t(n).

Finally, Möbius inversion extends to complex-valued functions on [1,+∞)[1,+\infty), not only arithmetic functions. The basic form is the special case in which the complex-valued functions vanish at all nonintegral points.

Extension 4

Let F(x)F(x) and G(x)G(x) be complex-valued functions on [1,+∞)[1,+\infty). Then

F(x)=∑n=1⌊x⌋G(xn)  ⟺  G(x)=∑n=1⌊x⌋μ(n)F(xn).F(x) = \sum_{n = 1}^{\lfloor x\rfloor}G\left(\dfrac{x}{n}\right) \iff G(x) = \sum_{n = 1}^{\lfloor x\rfloor}\mu(n)F\left(\dfrac{x}{n}\right).
Proof

Extend FF and GG to the region x<1x < 1, where they satisfy F(x)=G(x)=0F(x)=G(x)=0. Then the proposition is equivalent to:

F(x)=∑nG(xn)  ⟺  G(x)=∑nμ(n)F(xn).F(x) = \sum_n G\left(\dfrac{x}{n}\right) \iff G(x) = \sum_n \mu(n)F\left(\dfrac{x}{n}\right).

All these sums range over n∈N+n\in\mathbf N_+.

Direct verification gives:

∑nμ(n)F(xn)=∑nμ(n)∑dG(x/nd)=∑kG(xk)∑n∣kμ(n)=∑kG(xk)[k=1]=G(x).\begin{aligned} \sum_n \mu(n)F\left(\dfrac{x}{n}\right) &= \sum_n\mu(n)\sum_d G\left(\dfrac{x/n}{d}\right)\\ &= \sum_k G\left(\dfrac{x}{k}\right)\sum_{n\mid k}\mu(n)\\ &= \sum_k G\left(\dfrac{x}{k}\right)[k=1]\\ &= G(x). \end{aligned}

To obtain the second equality, set k=ndk = nd.

Corollary

Let f(n),g(n)f(n),g(n) be arithmetic functions. Then

f(n)=∑k=1ng(⌊nk⌋)  ⟺  g(n)=∑k=1nμ(k)f(⌊nk⌋).f(n) = \sum_{k=1}^ng\left(\left\lfloor\dfrac{n}{k}\right\rfloor\right) \iff g(n)=\sum_{k=1}^n\mu(k)f\left(\left\lfloor\dfrac{n}{k}\right\rfloor\right).
Proof

It suffices to take F(x)=f(⌊x⌋)F(x)=f(\lfloor x\rfloor) and G(x)=g(⌊x⌋)G(x)=g(\lfloor x\rfloor).

These extensions can be combined with one another to obtain more complicated inversion relations.

Dirichlet Prefix Sums

Prerequisite: prefix sums and differences

Consider the basic Möbius inversion relation:

f(n)=∑d∣ng(d)  ⟺  g(n)=∑d∣nμ(nd)f(d).f(n) = \sum_{d\mid n}g(d) \iff g(n) = \sum_{d\mid n}\mu\left(\dfrac{n}{d}\right)f(d).

In the left-hand equality, the value f(n)f(n) at nn is the sum of the values g(n)g(n) over its divisors. If a∣ba\mid b is interpreted as aa appearing before bb, then f(n)f(n) can be viewed as a kind of prefix sum of g(n)g(n). Thus, in domestic programming contests, the process in which {g(k)}k=1n\{g(k)\}_{k=1}^n is used to obtain {f(k)}k=1n\{f(k)\}_{k=1}^n is also called a Dirichlet prefix sum, and the reverse process is called a Dirichlet difference. These methods mostly arise when precomputing the values of an arithmetic function at the first NN points.

Next, consider computing Dirichlet prefix sums. If every prime is treated as a dimension, this is a high-dimensional prefix sum. Recall the dimension-by-dimension prefix-sum algorithm: traverse the dimensions one by one and add each position's value to its successor along that dimension. For arithmetic functions, this means traversing primes pp in increasing order and adding the function value at nn to npnp. This is the same traversal order as the Sieve of Eratosthenes. Therefore, this algorithm computes the Dirichlet prefix sum in O(nlog⁡log⁡n)O(n\log\log n) time for a sequence of length nn. Similarly, a dimension-by-dimension difference computes the Dirichlet difference in the same time complexity.

Reference Implementation

Dirichlet Prefix Sum

std::vector<int> dirichlet_presum(const std::vector<int>& g) {
  int n = g.size() - 1;
  std::vector<int> f(g);
  std::vector<bool> vis(n + 1);
  for (int x = 2; x <= n; ++x) {
    if (vis[x]) continue;
    for (int y = 1, xy = x; xy <= n; ++y, xy += x) {
      vis[xy] = true;
      f[xy] += f[y];
    }
  }
  return f;
}

Dirichlet Difference

std::vector<int> dirichlet_diff(const std::vector<int>& f) {
  int n = f.size() - 1;
  std::vector<int> g(f);
  std::vector<int> vis(n + 1);
  for (int x = 2; x <= n; ++x) {
    if (vis[x]) continue;
    for (int y = n / x, xy = x * y; y; --y, xy -= x) {
      vis[xy] = true;
      g[xy] -= g[y];
    }
  }
  return g;
}

This method can be extended to multiple sums (Extension 1), the multiplicative form (Extension 2), and replacing the constant function with a completely multiplicative function (the corollary of Extension 3), among others.

Examples

This section demonstrates applications of Möbius inversion and common transformation techniques. We begin with an example illustrating the basic technique for handling greatest-common-divisor conditions in a summation.

Luogu P2522 [HAOI 2011] Problem b

TT test cases. For each case, compute:

∑i=xn∑j=ym[gcd⁡(i,j)=k].\sum_{i=x}^{n}\sum_{j=y}^{m}[\gcd(i,j)=k].

Constraints: 1≤T,x,y,n,m,k≤5×1041\le T,x,y,n,m,k\le 5\times 10^4.

Solution

By inclusion–exclusion, the original expression can be split into 44 blocks, each having the form

f(n,m,k)=∑i=1n∑j=1m[gcd⁡(i,j)=k].f(n,m,k)=\sum_{i=1}^{n}\sum_{j=1}^{m}[\gcd(i,j)=k].

For expressions of this kind, the standard derivation is: factor out common divisors, apply properties of the Möbius function, and exchange the order of summation.

Since i,ji,j can only be multiples of kk, factor this out first—equivalently substitute i=ki′i=ki' and j=kj′j=kj', obtaining:

f(n,m,k)=∑i=1⌊n/k⌋∑j=1⌊m/k⌋[gcd⁡(i,j)=1].f(n,m,k)=\sum_{i=1}^{\lfloor n/k\rfloor}\sum_{j=1}^{\lfloor m/k\rfloor}[\gcd(i,j)=1].

By the Möbius-function identity,

[gcd⁡(i,j)=1]=∑d∣gcd⁡(i,j)μ(d)=∑d[d∣i][d∣j]μ(d).[\gcd(i,j)=1] = \sum_{d\mid\gcd(i,j)}\mu(d) = \sum_d[d\mid i][d\mid j]\mu(d).

Substituting this and exchanging the order of summation gives:

f(n,m,k)=∑dμ(d)(∑i=1⌊n/k⌋[d∣i])(∑j=1⌊m/k⌋[d∣j]).f(n,m,k)=\sum_d\mu(d)\left(\sum_{i=1}^{\lfloor n/k\rfloor}[d\mid i]\right)\left(\sum_{j=1}^{\lfloor m/k\rfloor}[d\mid j]\right).

The benefit is that, with dd fixed, the terms involving ii and jj separate and can be summed independently. Next, since

∑i=1⌊n/k⌋[d∣i]=⌊⌊n/k⌋d⌋, ∑j=1⌊m/k⌋[d∣j]=⌊⌊m/k⌋d⌋,\sum_{i=1}^{\lfloor n/k\rfloor}[d\mid i] = \left\lfloor\dfrac{\lfloor n/k\rfloor}{d}\right\rfloor,~\sum_{j=1}^{\lfloor m/k\rfloor}[d\mid j]=\left\lfloor\dfrac{\lfloor m/k\rfloor}{d}\right\rfloor,

Therefore,

f(n,m,k)=∑dμ(d)⌊⌊n/k⌋d⌋⌊⌊m/k⌋d⌋.f(n,m,k)=\sum_d\mu(d)\left\lfloor\dfrac{\lfloor n/k\rfloor}{d}\right\rfloor\left\lfloor\dfrac{\lfloor m/k\rfloor}{d}\right\rfloor.

After precomputing μ(d)\mu(d) with a linear sieve and its prefix sums, number-theoretic block decomposition solves the problem. The total time complexity is O(N+TN)O(N + T\sqrt{N}), where NN is the upper bound for n,mn,m, and TT is the number of test cases.

Reference Code
#include <algorithm>
#include <iostream>
using namespace std;
constexpr int N = 50000;
int mu[N + 5], p[N + 5];
bool flg[N + 5];

void init() {
  int tot = 0;
  mu[1] = 1;
  for (int i = 2; i <= N; ++i) {
    if (!flg[i]) {
      p[++tot] = i;
      mu[i] = -1;
    }
    for (int j = 1; j <= tot && i * p[j] <= N; ++j) {
      flg[i * p[j]] = true;
      if (i % p[j] == 0) {
        mu[i * p[j]] = 0;
        break;
      }
      mu[i * p[j]] = -mu[i];
    }
  }
  for (int i = 1; i <= N; ++i) mu[i] += mu[i - 1];
}

int solve(int n, int m) {
  int res = 0;
  for (int i = 1, j; i <= min(n, m); i = j + 1) {
    j = min(n / (n / i), m / (m / i));
    res += (mu[j] - mu[i - 1]) * (n / i) * (m / i);  // Formula derived above
  }
  return res;
}

int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  int T, a, b, c, d, k;
  init();  // Precompute the mu array
  cin >> T;
  for (int i = 1; i <= T; i++) {
    cin >> a >> b >> c >> d >> k;
    // By inclusion–exclusion, subtract the count in 1<=x<=b&&1<=y<=c-1 from the count in 1<=x<=b&&1<=y<=d, and
    //   add the count in 1<=x<=a-1&&1<=y<=c-1 to the count in 1<=x<=a-1&&1<=y<=d,
    //   obtaining the count in a<=x<=b&&c<=y<=d.
    // If this step is unclear, draw a coordinate diagram to understand it
    cout << solve(b / k, d / k) - solve(b / k, (c - 1) / k) -
                solve((a - 1) / k, d / k) + solve((a - 1) / k, (c - 1) / k)
         << '\n';
  }
  return 0;
}

The next two examples demonstrate enumerating common divisors and using a sieve to compute values of general multiplicative functions.

SPOJ LCMSUM

TT test cases. For each case, compute:

∑i=1nlcm⁡(i,n).\sum_{i=1}^n \operatorname{lcm}(i,n).

Constraints: 1≤T≤3×105, 1≤n≤1061\le T\le 3\times 10^5,~1\le n\le 10^6.

Solution 1

The problem gives a least common multiple, but a greatest common divisor is often easier to handle. First transform it:

f(n)=∑i=1nlcm⁡(i,n)=∑i=1ni⋅ngcd⁡(i,n).f(n)=\sum_{i=1}^n \operatorname{lcm}(i,n) = \sum_{i=1}^n \frac{i\cdot n}{\gcd(i,n)}.

Factor out nn and enumerate the greatest common divisor kk:

f(n)=n∑k∣n∑i=1nik[gcd⁡(i,n)=k].f(n)=n\sum_{k\mid n}\sum_{i=1}^n\dfrac{i}{k}[\gcd(i,n)=k].

For the inner sum, this is the standard greatest-common-divisor case; repeating the usual procedure gives:

f(n)=n∑k∣n∑i=1n/ki[gcd⁡(i,nk)=1]=n∑k∣n∑i=1n/ki∑dμ(d)[d∣i][d∣nk]=n∑k∣n∑dμ(d)[d∣nk](∑i=1n/ki[d∣i]).\begin{aligned} f(n) &= n\sum_{k\mid n}\sum_{i=1}^{n/k}i\left[\gcd\left(i,\dfrac{n}{k}\right)=1\right]\\ &= n\sum_{k\mid n}\sum_{i=1}^{n/k}i\sum_d\mu(d)[d\mid i]\left[d\mid \dfrac{n}{k}\right]\\ &= n\sum_{k\mid n}\sum_d\mu(d)\left[d\mid \dfrac{n}{k}\right]\left(\sum_{i=1}^{n/k}i[d\mid i]\right). \end{aligned}

Again, the sum over ii separates from the other terms and can be handled independently. The final sum is an arithmetic-progression sum (take i=di′i=di'):

∑i=1n/ki[d∣i]=d12(nkd+1)nkd=:dG(nkd).\sum_{i=1}^{n/k}i[d\mid i] = d\frac{1}{2}\left(\dfrac{n}{kd}+1\right)\dfrac{n}{kd}=:dG\left(\dfrac{n}{kd}\right).

This yields:

f(n)=n∑k∣n∑dμ(d)[d∣nk]dG(nkd).f(n) = n\sum_{k\mid n}\sum_d\mu(d)\left[d\mid \dfrac{n}{k}\right]dG\left(\dfrac{n}{kd}\right).

After enumerating common divisors, double sums of this form are common. Use the standard method: set the product to a new variable ℓ=kd\ell=kd, then exchange the order of summation again. Since d∣(n/k)d\mid(n/k) is equivalent to d∣ℓ∣nd\mid\ell\mid n, the expression becomes:

f(n)=n∑ℓ∣nG(nℓ)∑d∣ℓμ(d)d.f(n) = n\sum_{\ell\mid n}G\left(\dfrac{n}{\ell}\right)\sum_{d\mid\ell}\mu(d)d.

Let F(ℓ)=∑d∣ℓμ(d)dF(\ell)=\sum_{d\mid\ell}\mu(d)d; then the expression has the form:

f(n)=n∑ℓ∣nG(nℓ)F(ℓ).f(n) = n\sum_{\ell\mid n}G\left(\dfrac{n}{\ell}\right)F(\ell).

Since μ(d)d\mu(d)d is multiplicative, its convolution with the constant function 11, namely F(n)F(n), is also multiplicative. Although the sum above has the form of a Dirichlet convolution, G(n)G(n) is not multiplicative, so the whole sum is not multiplicative. However, G(n)G(n) is a polynomial, hence a linear combination of completely multiplicative functions. Thus,

f(n)=12n(∑ℓ(nℓ)2F(ℓ)+∑ℓnℓF(ℓ)).f(n) = \dfrac{1}{2}n\left(\sum_{\ell}\left(\dfrac{n}{\ell}\right)^2F(\ell) + \sum_{\ell}\dfrac{n}{\ell}F(\ell)\right).

Both terms (without their coefficients) are multiplicative and can be precomputed directly with a linear sieve (or the inner function can be sieved first and then preprocessed with a Dirichlet prefix sum in O(Nlog⁡log⁡N)O(N\log\log N) time). Specifically, let

Hs(n)=∑ℓ(nℓ)sF(ℓ), s=1,2.H_s(n) = \sum_{\ell}\left(\dfrac{n}{\ell}\right)^sF(\ell),~s=1,2.

To derive their expressions, it suffices to determine their values at prime powers. For a prime pp and positive exponent ee,

F(pe)=μ(1)+μ(p)p+∑j=2eμ(pj)pj=1−p,Hs(pe)=(pe)sF(1)+∑j=1e(pe−j)sF(pj)=pes+(1−p)1−pes1−ps, s=1,2.\begin{aligned} F(p^e) &= \mu(1) + \mu(p)p + \sum_{j=2}^e\mu(p^j)p^j = 1-p,\\ H_s(p^e) &= (p^e)^{s}F(1) + \sum_{j=1}^e(p^{e-j})^sF(p^j) = p^{es} + (1-p)\dfrac{1-p^{es}}{1-p^s},~s=1,2. \end{aligned}

In particular, H1(pe)≡1H_1(p^e)\equiv 1 is the constant function, while

H2(pe)=p2e+(1−p)1−p2e1−p2=H2(pe−1)+p2e−p2e−1.H_2(p^e) = p^{2e} + (1-p)\dfrac{1-p^{2e}}{1-p^2} = H_2(p^{e-1}) + p^{2e} - p^{2e-1}.

This is easy to solve with a linear sieve. After precomputing H2(n)H_2(n), a query can be answered using f(n)=(n/2)(H2(n)+1)f(n)=(n/2)(H_2(n)+1) in O(1)O(1) time. The total time complexity is O(N+T)O(N+T), where NN is the upper bound for nn and TT is the number of test cases.

The reference implementation derives the linear-sieve part further using the special form of this problem; this is not necessary. Using only the values at prime powers, preprocessing can still be completed in O(N)O(N) time. The derivation is given in Solution 2.

Solution 2

For this problem, there is a more flexible approach. Solution 1 shows that

f(n)=n∑k∣n∑i=1n/ki[gcd⁡(i,nk)=1]=n∑k∣nF(nk).f(n) = n\sum_{k\mid n}\sum_{i=1}^{n/k}i\left[\gcd\left(i,\dfrac{n}{k}\right)=1\right] = n\sum_{k\mid n}F\left(\dfrac{n}{k}\right).

Instead of continuing Möbius inversion here, observe that the following sum is actually the sum of integers not exceeding d=n/kd=n/k and coprime to it. For d>1d>1, the integers not exceeding dd that are coprime to it occur in pairs: ii and d−id-i are both coprime to dd, so

F(d)=∑i=1n′i[i⊥d]=∑i=1d(d−i)[i⊥d]=12d∑i=1d[i⊥d]=12dφ(d).F(d)=\sum_{i=1}^{n'}i[i\perp d] = \sum_{i=1}^{d}(d-i)[i\perp d] = \dfrac{1}{2}d\sum_{i=1}^{d}[i\perp d] = \dfrac{1}{2}d\varphi(d).

For d=1d=1,

F(d)=1=12+12dφ(d).F(d)=1=\dfrac{1}{2}+\dfrac{1}{2}d\varphi(d).

Therefore, the original expression can be written as

f(n)=12n(∑d∣ndφ(d)+1).f(n) = \dfrac{1}{2}n\left(\sum_{d\mid n}d\varphi(d) + 1\right).

Since G(n)=∑d∣ndφ(d)G(n)=\sum_{d\mid n}d\varphi(d) is the Dirichlet convolution of the multiplicative function nφ(n)n\varphi(n) with the constant function 11, it is multiplicative and can be precomputed with a linear sieve. It remains to determine its values at prime powers. For a prime pp and positive exponent ee,

G(pe)=1+∑i=1epe(pe−1)=G(pe−1)+p2e−p2e−1.G(p^e) = 1 + \sum_{i=1}^ep^e(p^e-1) = G(p^{e-1}) + p^{2e} - p^{2e-1}.

This agrees with the result derived in Solution 1. The total time complexity remains O(N+T)O(N+T).

Finally, the expression of this multiplicative function permits a further optimization of the linear sieve. For a prime pp,

G(p)=1−p+p2.G(p) = 1 - p + p^2.

For a general nn, the key to the linear sieve is computing G(pn)G(pn). This splits into two cases. When p⊥np\perp n, multiplicativity of GG gives

G(pn)=G(p)G(n).G(pn) = G(p)G(n).

Otherwise, when p∣np\mid n, write n=pemn=p^em with p⊥mp\perp m; then

G(pn)=G(pe+1)G(m)=G(pe)G(m)+(p2e+2−p2e+1)G(m)=G(n)+(p2e+2−p2e+1)G(m).\begin{aligned} G(pn) &= G(p^{e+1})G(m)\\ &= G(p^e)G(m) + (p^{2e+2} - p^{2e+1})G(m)\\ &= G(n) + (p^{2e+2} - p^{2e+1})G(m). \end{aligned}

Direct verification shows that this expression also holds when p⊥np\perp n. Therefore,

G(n)−G(np)=(p2e−p2e−1)G(m).G(n) - G\left(\dfrac{n}{p}\right) = (p^{2e}-p^{2e-1})G(m).

Substituting into the equation above gives

G(pn)=G(n)+p2(G(n)−G(np)).G(pn) = G(n) + p^2\left(G(n) - G\left(\dfrac{n}{p}\right)\right).

This simplifies the linear-sieve computation. The derivation is not necessary: for a multiplicative function without special properties, G(pn)=G(pe+1)G(m)G(pn)=G(p^{e+1})G(m) directly completes the linear sieve.

Reference Code
#include <iostream>
constexpr int N = 1000000;
int tot, p[N + 5];
long long g[N + 5];
bool flg[N + 5];  // Marker array

void solve() {
  g[1] = 1;
  for (int i = 2; i <= N; ++i) {
    if (!flg[i]) {
      p[++tot] = i;
      g[i] = (long long)1 * i * (i - 1) + 1;
    }
    for (int j = 1; j <= tot && i * p[j] <= N; ++j) {
      flg[i * p[j]] = true;
      if (i % p[j] == 0) {
        g[i * p[j]] =
            g[i] + (g[i] - g[i / p[j]]) * p[j] * p[j];  // Formula derived above
        break;
      }
      g[i * p[j]] = g[i] * g[p[j]];
    }
  }
}

using std::cin;
using std::cout;

int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  int T, n;
  solve();  // Precompute the g array
  cin >> T;
  for (int i = 1; i <= T; ++i) {
    cin >> n;
    cout << (g[n] + 1) * n / 2 << '\n';
  }
  return 0;
}
BZOJ 2154 [National Training Team] Crash's Number Table

Compute:

∑i=1n∑j=1mlcm⁡(i,j)mod  20101009.\sum_{i=1}^n\sum_{j=1}^m\operatorname{lcm}(i,j)\mod{20101009}.

Constraints: 1≤n,m≤1071\le n,m\le 10^7.

Solution

Ignore the modulus during the derivation. Let

f(n,m)=∑i=1n∑j=1mlcm⁡(i,j).f(n,m) = \sum_{i=1}^n\sum_{j=1}^m\operatorname{lcm}(i,j).

Again convert the least common multiple to a greatest common divisor, enumerate the divisor, and apply the standard procedure to obtain

f(n,m)=∑k∑i=1n∑j=1mijk[gcd⁡(i,j)=k]=∑k∑i=1⌊n/k⌋∑j=1⌊m/k⌋kij[gcd⁡(i,j)=1]=∑k∑i=1⌊n/k⌋∑j=1⌊m/k⌋kij∑dμ(d)[d∣i][d∣j]=∑kk∑dμ(d)(∑i=1⌊n/k⌋i[d∣i])(∑j=1⌊m/k⌋j[d∣j]).\begin{aligned} f(n,m) &= \sum_k\sum_{i=1}^n\sum_{j=1}^m\dfrac{ij}{k}[\gcd(i,j)=k] \\ &= \sum_k\sum_{i=1}^{\lfloor n/k\rfloor}\sum_{j=1}^{\lfloor m/k\rfloor} kij[\gcd(i,j)=1]\\ &= \sum_k\sum_{i=1}^{\lfloor n/k\rfloor}\sum_{j=1}^{\lfloor m/k\rfloor} kij\sum_d\mu(d)[d\mid i][d\mid j]\\ &= \sum_kk\sum_d\mu(d)\left(\sum_{i=1}^{\lfloor n/k\rfloor}i[d\mid i]\right)\left(\sum_{j=1}^{\lfloor m/k\rfloor}j[d\mid j]\right). \end{aligned}

Again, the sums over ii and jj separate. First compute these inner sums by extracting a factor (take i=di′i=di'); then

∑i=1⌊n/k⌋i[d∣i]=d∑i=1⌊⌊n/k⌋/d⌋i=dG(⌊⌊n/k⌋d⌋)=dG(⌊nkd⌋).\sum_{i=1}^{\lfloor n/k\rfloor}i[d\mid i] = d\sum_{i=1}^{\lfloor\lfloor n/k\rfloor/d\rfloor}i = dG\left(\left\lfloor\dfrac{\lfloor n/k\rfloor}{d}\right\rfloor\right) = dG\left(\left\lfloor\dfrac{n}{kd}\right\rfloor\right).

Here G(n)=12n(n+1)G(n)=\dfrac{1}{2}n(n+1) is the arithmetic-progression sum, and the final equality uses a property of the floor function. The other sum is symmetric. Substituting into the previous expression gives

f(n,m)=∑kk∑dμ(d)d2G(⌊nkd⌋)G(⌊mkd⌋).f(n,m) = \sum_k k\sum_{d}\mu(d)d^2G\left(\left\lfloor\dfrac{n}{kd}\right\rfloor\right)G\left(\left\lfloor\dfrac{m}{kd}\right\rfloor\right).

As before, expressions enumerating common divisors usually require enumerating the product ℓ=kd\ell = kd and exchanging the order of summation again:

f(n,m)=∑ℓ(∑d∣ℓμ(d)dℓ)G(⌊nℓ⌋)G(⌊mℓ⌋).f(n,m) = \sum_{\ell}\left(\sum_{d\mid\ell}\mu(d)d\ell\right)G\left(\left\lfloor\dfrac{n}{\ell}\right\rfloor\right)G\left(\left\lfloor\dfrac{m}{\ell}\right\rfloor\right).

Let

F(ℓ)=∑d∣ℓμ(d)dℓ.F(\ell) = \sum_{d\mid\ell}\mu(d)d\ell.

This is the product of the multiplicative function ℓ\ell and the multiplicative function ∑d∣ℓμ(d)d\sum_{d\mid\ell}\mu(d)d, so it is multiplicative. Precompute it and its prefix sums with a linear sieve, then use number-theoretic block decomposition to compute f(n,m)f(n,m). The total time complexity is O(min⁡{n,m})O(\min\{n,m\}).

Reference Code
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  constexpr int M = 20101009;
  int n, m;
  std::cin >> n >> m;
  if (n > m) std::swap(n, m);
  std::vector<int> f(n + 1), vis(n + 1), prime;
  prime.reserve(n);
  f[1] = 1;
  for (int x = 2; x <= n; ++x) {
    if (!vis[x]) {
      prime.emplace_back(x);
      f[x] = 1 - x;
    }
    for (int p : prime) {
      if (1LL * p * x > n) break;
      vis[x * p] = 1;
      f[x * p] = x % p ? (1 - p) * f[x] : f[x];
      if (x % p == 0) break;
    }
  }
  for (int x = 1; x <= n; ++x) {
    f[x] = 1LL * x * f[x] % M + M;
    f[x] = (f[x] + f[x - 1]) % M;
  }
  long long res = 0;
  for (int l = 1, r; l <= n; l = r + 1) {
    int nn = n / l, mm = m / l;
    r = std::min(n / nn, m / mm);
    int g_n = (1LL * nn * (nn + 1) / 2) % M;
    int g_m = (1LL * mm * (mm + 1) / 2) % M;
    res += 1LL * g_n * g_m % M * (f[r] - f[l - 1] + M) % M;
  }
  std::cout << (res % M) << '\n';
  return 0;
}

The next example is special and requires transforming the divisor-counting function of a product.

LOJ 2185. [SDOI2015] Sum of Divisor Counts

TT test cases. For each case, compute:

∑i=1n∑j=1mσ0(ij).\sum_{i=1}^n\sum_{j=1}^m\sigma_0(ij).

Here σ0(n)=∑d∣n1\sigma_0(n)=\sum_{d \mid n}1 denotes the number of divisors of nn.

Constraints: 1≤n,m,T≤5×1041\le n,m,T\le 5\times 10^4.

Solution

The difficulty is converting σ0(ij)\sigma_0(ij) into an expression involving greatest common divisors. Since σ0\sigma_0 is multiplicative, first consider prime powers. For a prime pp and nonnegative exponents e1,e2e_1,e_2, let i=pe1, j=pe2i=p^{e_1},~j=p^{e_2}; then

σ0(ij)=1+e1+e2=∑x∣i∑y∣j[x⊥y].\sigma_0(ij) = 1 + e_1 + e_2 = \sum_{x\mid i}\sum_{y\mid j}[x\perp y].

In general, write i=∏pipi=\prod_p i_p and j=∏pjpj=\prod_p j_p, where ip,jpi_p,j_p are the powers in the prime factorizations of i,ji,j, respectively, corresponding to the prime pp. Then

σ0(ij)=∏pσ0(ipjp)=∏p∑xp∣ip∑yp∣jp[xp⊥yp].\sigma_0(ij) = \prod_p\sigma_0(i_pj_p)= \prod_p\sum_{x_p\mid i_p}\sum_{y_p\mid j_p}[x_p\perp y_p].

Notice that, for each ii, enumerating its prime-power factors ipi_p and their divisors xpx_p is equivalent to enumerating ii's divisors xx and then decomposing them into all prime-power factors xpx_p; the same holds for jj. By distributivity, this gives

σ0(ij)=∑x∣i∑y∣j∏p[xp⊥yp]=∑x∣i∑y∣j[x⊥y].\sigma_0(ij) = \sum_{x\mid i}\sum_{y\mid j}\prod_p[x_p\perp y_p] = \sum_{x\mid i}\sum_{y\mid j}[x\perp y].

conclusion:x⊥yx\perp y,if and only ifForeach pp, xp⊥ypx_p\perp y_p .

obtain , canApplications :

σ0(ij)=∑x∣i∑y∣j[x⊥y]=∑x∣i∑y∣j∑dμ(d)[d∣x][d∣y]=∑dμ(d)(∑x[d∣x∣i])(∑y[d∣y∣j])=∑dμ(d)[d∣i][d∣j]σ0(id)σ0(jd).\begin{aligned} \sigma_0(ij) &= \sum_{x\mid i}\sum_{y\mid j}[x\perp y]\\ &= \sum_{x\mid i}\sum_{y\mid j}\sum_d\mu(d)[d\mid x][d\mid y]\\ &= \sum_d\mu(d)\left(\sum_{x}[d\mid x\mid i]\right)\left(\sum_{y}[d\mid y\mid j]\right)\\ &= \sum_d\mu(d)[d\mid i][d\mid j]\sigma_0\left(\dfrac{i}{d}\right)\sigma_0\left(\dfrac{j}{d}\right). \end{aligned}

:function d∣id\mid i d∣jd\mid j nonzerovalue, , satisfy d∣x∣id\mid x\mid i xx When id\dfrac{i}{d} xd\dfrac{x}{d}, satisfy d∣y∣jd\mid y\mid j yy .

, findsum :

f(n,m)=∑i=1n∑j=1mσ0(ij)=∑i=1n∑j=1m∑dμ(d)[d∣i][d∣j]σ0(id)σ0(jd)=∑dμ(d)(∑i=1n[d∣i]σ0(id))(∑j=1m[d∣j]σ0(jd))=∑dμ(d)(∑i=1⌊n/d⌋σ0(i))(∑j=1⌊m/d⌋σ0(j)).\begin{aligned} f(n,m) &= \sum_{i=1}^n\sum_{j=1}^m\sigma_0(ij)\\ &= \sum_{i=1}^n\sum_{j=1}^m\sum_d\mu(d)[d\mid i][d\mid j]\sigma_0\left(\dfrac{i}{d}\right)\sigma_0\left(\dfrac{j}{d}\right)\\ &= \sum_d\mu(d)\left(\sum_{i=1}^n[d\mid i]\sigma_0\left(\dfrac{i}{d}\right)\right)\left(\sum_{j=1}^m[d\mid j]\sigma_0\left(\dfrac{j}{d}\right)\right)\\ &= \sum_d\mu(d)\left(\sum_{i=1}^{\lfloor n/d\rfloor}\sigma_0(i)\right)\left(\sum_{j=1}^{\lfloor m/d\rfloor}\sigma_0(j)\right). \end{aligned}

Let G(n)=∑i=1nσ0(i)G(n)=\sum_{i=1}^n\sigma_0(i),

f(n,m)=∑dμ(d)G(⌊nd⌋)G(⌊md⌋).f(n,m)=\sum_{d}\mu(d)G\left(\left\lfloor\dfrac{n}{d}\right\rfloor\right)G\left(\left\lfloor\dfrac{m}{d}\right\rfloor\right).

canbynumber theoryblock decompositionfind . need to μ(n)\mu(n) sum σ0(n)\sigma_0(n) prefix sum . time complexity O(N+TN)O(N+T\sqrt{N}),where,NN n,mn,m ,TT .

Referencescode
#include <algorithm>
#include <iostream>
using namespace std;
constexpr long long N = 5e4 + 5;
long long n, m, T, pr[N], mu[N], d[N], t[N],
    cnt;  // t denotes the number of times the smallest prime factor of i occurs.
bool bp[N];

void prime_work(long long k) {
  bp[0] = bp[1] = true, mu[1] = 1, d[1] = 1;
  for (long long i = 2; i <= k; i++) {  // Linear sieve.
    if (!bp[i]) pr[++cnt] = i, mu[i] = -1, d[i] = 2, t[i] = 1;
    for (long long j = 1; j <= cnt && i * pr[j] <= k; j++) {
      bp[i * pr[j]] = true;
      if (i % pr[j] == 0) {
        mu[i * pr[j]] = 0;
        d[i * pr[j]] = d[i] / (t[i] + 1) * (t[i] + 2);
        t[i * pr[j]] = t[i] + 1;
        break;
      } else {
        mu[i * pr[j]] = -mu[i];
        d[i * pr[j]] = d[i] << 1;
        t[i * pr[j]] = 1;
      }
    }
  }
  for (long long i = 2; i <= k; i++)
    mu[i] += mu[i - 1], d[i] += d[i - 1];  // Compute prefix sums.
}

long long solve() {
  long long res = 0, mxi = min(n, m);
  for (long long i = 1, j; i <= mxi; i = j + 1) {  // Division into quotient blocks.
    j = min(n / (n / i), m / (m / i));
    res += d[n / i] * d[m / i] * (mu[j] - mu[i - 1]);
  }
  return res;
}

int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  cin >> T;
  prime_work(50000);  // Precompute.
  while (T--) {
    cin >> n >> m;
    cout << solve() << '\n';
  }
  return 0;
}

Example Applicationsmultiplication Möbius inversion.

Luogu P5221 Product

findvalue:

∏i=1n∏j=1nlcm⁡(i,j)gcd⁡(i,j)(mod104857601).\prod_{i=1}^n\prod_{j=1}^n\dfrac{\operatorname{lcm}(i,j)}{\gcd(i,j)}\pmod{104857601}.

range:1≤n≤1×1061\le n\le 1\times 10^6.

Note

process .Let

f(n)=∏i=1n∏j=1nlcm⁡(i,j)gcd⁡(i,j).f(n) = \prod_{i=1}^n\prod_{j=1}^n\dfrac{\operatorname{lcm}(i,j)}{\gcd(i,j)}.

minimum multiple maximum :

f(n)=∏i=1n∏j=1nij(gcd⁡(i,j))2.f(n) = \prod_{i=1}^n\prod_{j=1}^n\dfrac{ij}{(\gcd(i,j))^2}.

Note, product independent ,canrespectivelycalculate.Let

g(n)=∏i=1n∏j=1ngcd⁡(i,j).g(n) = \prod_{i=1}^n\prod_{j=1}^n\gcd(i,j).

:

f(n)=(n!)2ng(n)2.f(n) = \dfrac{(n!)^{2n}}{g(n)^2}.

g(n)g(n) calculateproblem. sum ,Howeverneed to corresponding multiplication . , :

g(n)=∏k∏i=1n∏j=1nk↑[gcd⁡(i,j)=k]=∏k∏i=1⌊n/k⌋∏j=1⌊n/k⌋k↑[gcd⁡(i,j)=1].\begin{aligned} g(n) &= \prod_k\prod_{i=1}^n\prod_{j=1}^nk\uparrow[\gcd(i,j)=k]\\ &= \prod_k\prod_{i=1}^{\lfloor n/k\rfloor}\prod_{j=1}^{\lfloor n/k\rfloor}k\uparrow[\gcd(i,j)=1]. \end{aligned}

where,a↑b=aba\uparrow b=a^b Knuth . , [gcd⁡(i,j)=1]=∑dμ(d)[d∣i][d∣j][\gcd(i,j)=1]=\sum_d\mu(d)[d\mid i][d\mid j], sum product ,obtain:

g(n)=∏k∏d∏i=1⌊n/k⌋∏j=1⌊n/k⌋k↑(μ(d)[d∣i][d∣j]).g(n) = \prod_k\prod_d\prod_{i=1}^{\lfloor n/k\rfloor}\prod_{j=1}^{\lfloor n/k\rfloor}k\uparrow(\mu(d)[d\mid i][d\mid j]).

( Let i=di′i=di',j=dj′j=dj'), Applications function property, obtain:

g(n)=∏k∏d∏i=1⌊n/(kd)⌋∏j=1⌊n/(kd)⌋k↑μ(d).g(n) = \prod_k\prod_d\prod_{i=1}^{\lfloor n/(kd)\rfloor}\prod_{j=1}^{\lfloor n/(kd)\rfloor}k\uparrow\mu(d).

with respect to i,ji,j product, i,ji,j,Therefore When :

g(n)=∏k∏dk↑(μ(d)⌊nkd⌋2).g(n) = \prod_k\prod_d k\uparrow\left(\mu(d)\left\lfloor\dfrac{n}{kd}\right\rfloor^2\right).

because , For need to findproduct .Let ℓ=kd\ell = kd, :

g(n)=∏ℓ∏d∣ℓ(ℓd)↑(μ(d)⌊nℓ⌋2)=∏ℓ(∏d∣ℓ(ℓd)↑μ(d))↑⌊nℓ⌋2.\begin{aligned} g(n) &= \prod_{\ell}\prod_{d\mid\ell}\left(\dfrac{\ell}{d}\right)\uparrow\left(\mu(d)\left\lfloor\dfrac{n}{\ell}\right\rfloor^2\right)\\ &= \prod_\ell\left(\prod_{d\mid\ell}\left(\dfrac{\ell}{d}\right)\uparrow\mu(d)\right)\uparrow\left\lfloor\dfrac{n}{\ell}\right\rfloor^2. \end{aligned}

Let

F(n)=∏d∣n(nd)↑μ(d).F(n) = \prod_{d\mid n}\left(\dfrac{n}{d}\right)\uparrow\mu(d).

It is easy to with respect to F~(n)=n\tilde F(n)=n product Möbius inversion. , canApplications Dirichlet difference method O(nlog⁡log⁡n)O(n\log\log n) .When ,Because F~(n)\tilde F(n) simple,F(n)F(n) candirectlyfind :

F(n)={p,n=pe, p∈P, e∈N+,1,otherwise.F(n) = \begin{cases} p, & n = p^e,~p\in\mathbf P,~e\in\mathbf N_+, \\ 1, &\text{otherwise}. \end{cases}

von Mangoldt function .obtain F(n)F(n) value ,directlyApplicationsproduct number theoryblock decomposition can O(n)O(\sqrt{n}) find g(n)g(n) value, obtain f(n)f(n) value. time complexity O(n)O(n).

value Note , product calculate ,oftenneed to ,Therefore the same.

Note

product productsum ,Therefore,For problem, can .For , Consider g(n)g(n) . , :

log⁡g(n)=∑i=1n∑j=1nlog⁡gcd⁡(i,j).\log g(n) = \sum_{i=1}^n\sum_{j=1}^n\log\gcd(i,j).

For maximum ,directlyApplications , obtain:

log⁡g(n)=∑klog⁡k∑i=1n∑j=1n[gcd⁡(i,j)=k]=∑klog⁡k∑i=1⌊n/k⌋∑j=1⌊n/k⌋[gcd⁡(i,j)=1]=∑klog⁡k∑dμ(d)(∑i=1⌊n/k⌋[i∣d])(∑j=1⌊n/k⌋[j∣d])=∑klog⁡k∑dμ(d)⌊nkd⌋2=∑ℓ(∑dμ(d)log⁡ℓd)⌊nℓ⌋2=∑ℓΛ(ℓ)⌊nℓ⌋2.\begin{aligned} \log g(n) &= \sum_k\log k\sum_{i=1}^n\sum_{j=1}^n[\gcd(i,j)=k]\\ &= \sum_k\log k\sum_{i=1}^{\lfloor n/k\rfloor}\sum_{j=1}^{\lfloor n/k\rfloor}[\gcd(i,j)=1]\\ &= \sum_k\log k\sum_d\mu(d)\left(\sum_{i=1}^{\lfloor n/k\rfloor}[i\mid d]\right)\left(\sum_{j=1}^{\lfloor n/k\rfloor}[j\mid d]\right)\\ &= \sum_k\log k\sum_d\mu(d)\left\lfloor\dfrac{n}{kd}\right\rfloor^2\\ &= \sum_{\ell}\left(\sum_d\mu(d)\log\dfrac{\ell}{d}\right)\left\lfloor\dfrac{n}{\ell}\right\rfloor^2\\ &= \sum_{\ell}\Lambda(\ell)\left\lfloor\dfrac{n}{\ell}\right\rfloor^2. \end{aligned}

where,Λ(n)\Lambda(n) von Mangoldt function. , obtain .

Referencescode
#include <algorithm>
#include <iostream>
#include <vector>

int pow(int a, int b, int m) {
  int res = 1;
  for (int po = a; b; b >>= 1) {
    if (b & 1) res = 1LL * res * po % m;
    po = 1LL * po * po % m;
  }
  return res;
}

int main() {
  constexpr int M = 104857601;
  int n;
  std::cin >> n;
  // Get F(n), i.e., exp(Lambda(n)).
  std::vector<int> vis(n + 1), prime, pf(n + 1), rem(n + 1);
  prime.reserve(n);
  for (int x = 2; x <= n; ++x) {
    if (!vis[x]) {
      prime.emplace_back(x);
      pf[x] = x;
      rem[x] = 1;
    }
    for (int p : prime) {
      if (1LL * p * x > n) break;
      vis[x * p] = 1;
      pf[x * p] = p;
      rem[x * p] = x % p ? x : rem[x];
      if (x % p == 0) break;
    }
  }
  pf[1] = 1;
  for (int x = 2; x <= n; ++x) {
    pf[x] = rem[x] == 1 ? pf[x] : 1;
  }
  // Prefix products and their inverses.
  std::vector<int> pm(n + 1), ip(n + 1);
  pm[0] = 1;
  for (int x = 1; x <= n; ++x) {
    pm[x] = 1LL * pm[x - 1] * pf[x] % M;
  }
  int inv = pow(pm[n], M - 2, M);
  ip[0] = 1;
  for (int x = n; x >= 1; --x) {
    ip[x] = inv;
    inv = 1LL * inv * pf[x] % M;
  }
  // Calculate g(n).
  int res = 1;
  for (int l = 1, r; l <= n; l = r + 1) {
    r = n / (n / l);
    int a = 1LL * pm[r] * ip[l - 1] % M;
    int b = 1LL * (n / l) * (n / l) % (M - 1);
    res = 1LL * res * pow(a, b, M) % M;
  }
  // Take square and then inverse.
  res = pow(res, M - 3, M);
  // Get factorials.
  int fac = 1;
  for (int x = 1; x <= n; ++x) {
    fac = 1LL * fac * x % M;
  }
  // Final answer.
  res = 1LL * res * pow(fac, 2 * n, M) % M;
  std::cout << res << std::endl;
  return 0;
}

Exercises

References

This content comes from OI Wiki: Möbius Inversion. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.