杜教筛第一题。
数学推导过程详见这里
具体实现的时候要用一个hash表或者map存一下,其实感觉两个东西差不多快。想要提高速度应该调一调M的大小,可以三分试一试呀。
#include<bits/stdc++.h>
#define ll long long
#define M 4500000
using namespace std;
int prime[M+5],notp[M+5],cnt;
ll mu[M+5],phi[M+5],T,n;
map <int,ll> mpphi,mpmu;
inline char nc()
{
static char buf[100000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline ll read()
{
ll x=0,b=1;
char c=nc();
for(;!(c<='9'&&c>='0');c=nc())if(c=='-')b=-1;
for(;c<='9'&&c>='0';c=nc())x=x*10+c-'0';
return x*b;
}
inline void init()
{
notp[1]=true,mu[1]=1,phi[1]=1;
for(int i=1;i<=M;i++)
{
if(!notp[i])prime[++cnt]=i,mu[i]=-1,phi[i]=i-1;
for(int j=1;j<=cnt&&i*prime[j]<=M;j++)
{
notp[i*prime[j]]=true;
if(i%prime[j]==0)
{
mu[i*prime[j]]=0;
phi[i*prime[j]]=phi[i]*prime[j];
break;
}
mu[i*prime[j]]=-mu[i];
phi[i*prime[j]]=phi[i]*phi[prime[j]];
}
}
for(int i=1;i<=M;i++)phi[i]+=phi[i-1],mu[i]+=mu[i-1];
}
inline ll getphi(ll x)
{
if(x<=M)return phi[x];
if(mpphi[x])return mpphi[x];
ll tmp;
tmp=x*(x+1)/2;
int lst;
for(int i=2;i<=x;i=lst+1)
{
lst=x/(x/i);
tmp-=getphi(x/i)*(ll)(lst-i+1);
if(x==lst)break;
}
mpphi[x]=tmp;
return tmp;
}
inline ll getmu(ll x)
{
if(x<=M)return mu[x];
if(mpmu[x])return mpmu[x];
ll tmp;
tmp=1;
int lst;
for(int i=2;i<=x;i=lst+1)
{
lst=x/(x/i);
tmp-=getmu(x/i)*(ll)(lst-i+1);
if(x==lst)break;
}
mpmu[x]=tmp;
return tmp;
}
int main()
{
freopen("in.txt","r",stdin);
init();T=read();
while(T--)
{
n=read();
printf("%lld %lld\n",getphi(n),getmu(n));
}
return 0;
}