正题
题目链接:https://www.luogu.com.cn/problem/P4213
题目大意
给出nnn,求∑i=1nφ(i)\sum_{i=1}^n\varphi(i)i=1∑nφ(i)
和
∑i=1nμ(i)\sum_{i=1}^n\mu(i)i=1∑nμ(i)
解题思路
考虑如何将φ\varphiφ卷起来,我们可以乘上一个函数I(I(x)=1)I(I(x)=1)I(I(x)=1),就有
(φ∗I)(n)=∑d∣nφ(d)I(nd)(\varphi*I)(n)=\sum_{d|n}\varphi(d)I(\frac{n}{d})(φ∗I)(n)=∑d∣nφ(d)I(dn)
变成杜教筛的式子之后就是
I(1)S(n)=∑i=1n(φ∗I)(n)−∑i=2nI(i)∗S(⌊ni⌋)I(1)S(n)=\sum_{i=1}^n(\varphi*I)(n)-\sum_{i=2}^nI(i)*S(\lfloor \frac{n}{i}\rfloor)I(1)S(n)=i=1∑n(φ∗I)(n)−i=2∑nI(i)∗S(⌊in⌋)
整除分块计算下去就好了。
μ\muμ同理
codecodecode
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#define ll long long
using namespace std;
const ll N=1e7+1;
ll T,n,cnt,mu[N],phi[N],pri[N];
bool vis[N];
map<ll,ll> sp,sm;
void prime(){mu[1]=phi[1]=1;for(ll i=2;i<N;i++){if(!vis[i])pri[++cnt]=i,mu[i]=-1,phi[i]=i-1;for(ll j=1;j<=cnt&&pri[j]*i<N;j++){vis[pri[j]*i]=1;if(i%pri[j]==0){phi[i*pri[j]]=phi[i]*pri[j];break;}phi[i*pri[j]]=phi[pri[j]]*phi[i];mu[i*pri[j]]=-mu[i];}}for(ll i=1;i<N;i++)phi[i]+=phi[i-1],mu[i]+=mu[i-1];return;
}
ll GetSphi(ll n){if(n<N)return phi[n];if(sp[n])return sp[n];ll rest=n*(n+1ll)/2ll;for(ll l=2ll,r;l<=n;l=r+1ll)r=n/(n/l),rest-=(r-l+1ll)*GetSphi(n/l);return (sp[n]=rest);
}
ll GetSmul(ll n){if(n<N)return mu[n];if(sm[n])return sm[n];ll rest=1ll;for(ll l=2ll,r;l<=n;l=r+1ll)r=n/(n/l),rest-=(r-l+1ll)*GetSmul(n/l);return (sm[n]=rest);
}
int main()
{scanf("%lld",&T);prime();while(T--){scanf("%lld",&n);printf("%lld %lld\n",GetSphi(n),GetSmul(n));}
}