给定一个正整数N(N\le2^{31}-1)N(N≤231−1)
求ans_1=\sum_{i=1}^n\phi(i),ans_2=\sum_{i=1}^n \mu(i)ans1=∑i=1nϕ(i),ans2=∑i=1nμ(i)
输入格式:
一共T+1行 第1行为数据组数T(T<=10) 第2~T+1行每行一个非负整数N,代表一组询问
输出格式:
一共T行,每行两个用空格分隔的数ans1,ans2
输入样例#1
6
1
2
8
13
30
2333
输出样例#1:
1 1
2 0
22 -2
58 -3
278 -3
1655470 2
裸的杜教筛
\sum_{i=1}^{n}\varphi(i) = \frac{n\times(n+1)}{2} - \sum_{d=2}^{n}\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\varphi(i)
\sum_{i=1}^{n}\mu(i) = 1 - \sum_{d=2}^{n}\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\mu(i)
然后直接暴力递归计算即可
#include<cstdio>
#include<map>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#define LL long long
using namespace std;
using namespace __gnu_pbds;
const int MAXN=5000030;
int N,limit=5000000,tot=0,vis[MAXN],mu[MAXN],prime[MAXN];
LL phi[MAXN];
gp_hash_table<int,LL>Aphi,Amu;
void GetMuAndPhi()
{
vis[1]=1;phi[1]=1;mu[1]=1;
for(int i=1;i<=limit;i++)
{
if(!vis[i]) prime[++tot]=i,phi[i]=i-1,mu[i]=-1;
for(int j=1;j<=tot&&i*prime[j]<=limit;j++)
{
vis[i*prime[j]]=1;
if(i%prime[j]==0){mu[i*prime[j]]=0; phi[i*prime[j]]=phi[i]*prime[j]; break;}
else {mu[i*prime[j]]=-mu[i]; phi[i*prime[j]]=phi[i]*(prime[j]-1); }
}
}
for(int i=1;i<=limit;i++) mu[i]+=mu[i-1],phi[i]+=phi[i-1];
}
LL SolvePhi(LL n)
{
if(n<=limit) return phi[n];
if(Aphi[n]) return Aphi[n];
LL tmp=n*(n+1)/2;
for(int i=2,nxt;i<=n;i=nxt+1)
nxt=min(n,n/(n/i)),
tmp-=SolvePhi(n/i)*(LL)(nxt-i+1);
return Aphi[n]=tmp;
}
LL SolveMu(LL n)
{
if(n<=limit) return mu[n];
if(Amu[n]) return Amu[n];
LL tmp=1;
for(int i=2,nxt;i<=n;i=nxt+1)
nxt=min(n,n/(n/i)),
tmp-=SolveMu(n/i)*(LL)(nxt-i+1);
return Amu[n]=tmp;
}
int main()
{
GetMuAndPhi();
int QWQ;
scanf("%d",&QWQ);
while(QWQ--)
{
scanf("%lld",&N);
printf("%lld %lld\n",SolvePhi(N),SolveMu(N));
}
return 0;
}