bzoj2818 GCD(莫比乌斯反演)

文章目录

  • 题意
  • 题解
  • 代码

别说这么水的题居然还有人写博客。不是我水博客,是这种推式子的题没有latex我根本推不出来。


题意

∑ i = 1 N ∑ j = 1 N [ g c d ( i , j ) ∈ P ] , N ≤ 1 0 7 \sum_{i=1}^{N}\sum_{j=1}^{N}[gcd(i,j)\in \mathbb{P}],N\le 10^7 i=1Nj=1N[gcd(i,j)P],N107

题解

推式子,首先枚举 p p p

∑ p ∈ P , p ≤ N ∑ i = 1 ⌊ N p ⌋ ∑ j = 1 ⌊ N p ⌋ [ g c d ( i , j ) = 1 ] \sum_{p\in \mathbb{P},p\le N}\sum_{i=1}^{\lfloor \frac{N}{p} \rfloor}\sum_{j=1}^{\lfloor \frac{N}{p} \rfloor}[gcd(i,j)=1] pP,pNi=1pNj=1pN[gcd(i,j)=1]

拿出莫比乌斯函数

∑ p ∈ P , p ≤ N ∑ i = 1 ⌊ N p ⌋ ∑ j = 1 ⌊ N p ⌋ ∑ d ∣ i , d ∣ j μ ( d ) \sum_{p\in \mathbb{P},p\le N}\sum_{i=1}^{\lfloor \frac{N}{p} \rfloor}\sum_{j=1}^{\lfloor \frac{N}{p} \rfloor}\sum_{d|i,d|j}\mu(d) pP,pNi=1pNj=1pNdi,djμ(d)

套路,枚举 d d d

∑ p ∈ P , p ≤ N ∑ d = 1 ⌊ N p ⌋ μ ( d ) ⌊ N p d ⌋ 2 \sum_{p\in \mathbb{P},p\le N}\sum_{d=1}^{\lfloor \frac{N}{p} \rfloor}\mu(d)\lfloor \frac{N}{pd} \rfloor^2 pP,pNd=1pNμ(d)pdN2

再套路,枚举 T = p d T=pd T=pd

∑ T = 1 N ⌊ N T ⌋ 2 ∑ p ∣ T , p ∈ P μ ( T p ) \sum_{T=1}^{N}\lfloor \frac{N}{T} \rfloor^2\sum_{p|T,p\in\mathbb{P}}\mu(\frac{T}{p}) T=1NTN2pT,pPμ(pT)

f ( T ) = ∑ p ∣ T , p ∈ P μ ( T p ) f(T)=\sum_{p|T,p\in\mathbb{P}}\mu(\frac{T}{p}) f(T)=pT,pPμ(pT),尝试求 f f f的递推式。

考虑套用线性筛求积性函数的方法,发现(p是质数)

{ f ( p ) = 1 ( 1 ) f ( i ⋅ p ) = { − f ( i ) + μ ( i ) , p ∤ i ( 2 ) μ ( i ) , p ∣ i ( 3 ) \left\{ \begin{aligned} &f(p)=1&(1)\\ &f(i\cdot p)= \left\{ \begin{aligned} &-f(i)+\mu(i), &p\nmid i &(2)\\ &\mu(i), &p\mid i & (3) \end{aligned} \right. \end{aligned} \right. f(p)=1f(ip)={f(i)+μ(i),μ(i),pipi(2)(3)(1)

理解很简单,首先自变量是质数的时候 f ( p ) = μ ( 1 ) = 1 f(p)=\mu(1)=1 f(p)=μ(1)=1

然后当 p ∤ i p\nmid i pi时,对所有 i i i的质因子 d d d,贡献由 μ ( i d ) \mu(\frac{i}{d}) μ(di)变成了 μ ( i ⋅ p d ) \mu(\frac{i\cdot p}{d}) μ(dip),因为p不是i的质因子,所以 μ ( i ⋅ p d ) = − μ ( i d ) \mu(\frac{i\cdot p}{d})=-\mu(\frac{i}{d}) μ(dip)=μ(di),然后还要再多枚举一个新的质数p,加上 μ ( i ⋅ p p ) = μ ( i ) \mu(\frac{i\cdot p}{p})=\mu(i) μ(pip)=μ(i)

p ∣ i p\mid i pi时,多了一个质因子使得部分莫比乌斯函数变成0, f ( i ⋅ p ) = ∑ d ∣ i , d ∈ P , d = ̸ p μ ( i ⋅ p d ) + μ ( i ) = 0 + μ ( i ) f(i\cdot p)=\sum_{d|i,d\in\mathbb{P},d=\not p}\mu(\frac{i\cdot p}{d})+\mu(i)=0+\mu(i) f(ip)=di,dP,d≠pμ(dip)+μ(i)=0+μ(i)

所以这题 O ( n ) O(n) O(n)递推解决。

代码

#include
using namespace std;
typedef long long LL;
const int N = 1e7 + 1;
int n, mu[N], p[N], pn, f[N];
bool vis[N];
LL ans;

void init()
{
	mu[1] = 1;
	for (int i = 2; i <= n; ++ i){
		if (!vis[i]){
			p[++pn] = i;
			mu[i] = -1;
			f[i] = 1;
		}
		for (int j = 1; j <= pn; ++ j){
			if (1LL * p[j] * i > n) break;
			vis[p[j]*i] = 1;
			if (i % p[j] == 0){
				mu[i*p[j]] = 0;
				f[i*p[j]] = mu[i];
				break;
			}
			else{
				mu[i*p[j]] = -mu[i];
				f[i*p[j]] = -f[i] + mu[i];
			}
		}
	}
	for (int i = 1; i <= n; ++ i)
		ans += 1LL * (n/i) * (n/i) * f[i];
}

int main()
{
	scanf("%d", &n);
	init();
	printf("%lld\n", ans);
}

你可能感兴趣的:(题解)