跳到正文

题解

AT_xmascon19_d Sum of (-1)^f(n)

Rigel约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年3月30日
收录
2026年3月31日
更新
2026年11月8日
篇幅
约 4 分钟
获赞
12

版本

  1. v2当前
  2. v1

前置知识:Min_25 筛。

默认读者已经掌握 Min_25 筛。

题意

给定 NN,求:

∑i=1Nλ(i).\sum\limits_{i=1}^{N} \lambda(i).

其中 λ\lambda 为 Liouville 函数,定义为:

λ(n)=(−1)Ω(n).\lambda(n) = (-1)^{\Omega(n)}.

其中 Ω(n)\Omega(n) 为 nn 的质因数个数(计重)。

思路

显然 Ω\Omega 为加性函数,故 λ\lambda 为积性函数。

考虑 Min_25 筛。

对于质数 pp,λ(p)=(−1)Ω(p)=−1\lambda(p) = (-1)^{\Omega(p)} = -1,λ(pc)=(−1)Ω(pc)=(−1)c\lambda(p^c) = (-1)^{\Omega(p^c)} = (-1)^c。

令 g(p)=1g(p) = 1,则 λ(p)=−g(p)\lambda(p) = -g(p)。

然后就可以做了。

时间复杂度为 Θ(N1−ε)\Theta(N^{1 - \varepsilon})。

Code

C++
#include<bits/stdc++.h>
#define int long long

const int B=3.2e5+10;

using namespace std;

int T;

int n,b,ans;

int cnt,p[B];

bool vis[B];

int s[B];

int tot,w[B<<1];

int id1[B],id2[B];

int g[B<<1];

inline int read(){
	int ret=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9')ret=ret*10+(ch&15),ch=getchar();
	return ret*f;
}

int _sqrt(int x){
	int ret=floor(sqrtl(x));
	while((ret+1)*(ret+1)<=x)ret++;
	return ret;
}

int get_id(int _n){
	if(_n<=b)return id1[_n];
	return id2[n/_n];
}

void _init(){
	for(int i=2;i<=b;i++){
		if(!vis[i]){
			p[++cnt]=i;
			s[cnt]=s[cnt-1]+1;
		}
		for(int j=1;j<=cnt&&i*p[j]<=b;j++){
			vis[i*p[j]]=1;
			if(!(i%p[j]))break;
		}
	}
	for(int l=1,r;l<=n;l=r+1){
		r=n/(n/l);
		int _n=n/l;
		w[++tot]=_n;
		if(_n<=b)id1[_n]=tot;
		else id2[n/_n]=tot;
		g[tot]=_n-1;
	}
	for(int k=1;k<=cnt;k++){
		for(int i=1;i<=tot&&p[k]*p[k]<=w[i];i++){
			int id=get_id(w[i]/p[k]);
			g[i]-=g[id]-s[k-1];
		}
	}
}

int F(int k,int _n){
	if(_n<p[k])return 0;
	int id=get_id(_n);
	int ret=(g[id]-s[k-1])*(-1);
	for(int i=k;i<=cnt&&p[i]*p[i]<=_n;i++){
		for(int c=1,_p=p[i];_p*p[i]<=_n;c++,_p*=p[i]){
			ret+=((c&1)?1:-1)+((c&1)?-1:1)*F(i+1,_n/_p);
		}
	}
	return ret;
}

signed main(){
	n=read();
	b=_sqrt(n);
	_init();
	ans=F(1,n)+1;
	printf("%lld\n",ans);
	return 0;
}
原文