题目描述
题解
杜教筛裸题
我不会手写hash表…
讲解移步:http://blog.csdn.net/clove_unique/article/details/66991109
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
#define N 5000000
#define LL long long
int T,n;
int p[N+3],prime[N+3];LL phi[N+3],mu[N+3];
map <int,LL> ansphi,ansmu;
void get()
{
phi[1]=mu[1]=1;
for (int i=2;i<=N;++i)
{
if (!p[i])
{
prime[++prime[0]]=i;
phi[i]=i-1;
mu[i]=-1;
}
for (int j=1;j<=N&&i*prime[j]<=N;++j)
{
p[i*prime[j]]=1;
if (i%prime[j]==0)
{
phi[i*prime[j]]=phi[i]*prime[j];
mu[i*prime[j]]=0;
break;
}
else
{
phi[i*prime[j]]=phi[i]*phi[prime[j]];
mu[i*prime[j]]=-mu[i];
}
}
}
for (int i=1;i<=N;++i) phi[i]+=phi[i-1],mu[i]+=mu[i-1];
}
LL sumphi(LL n)
{
if (n<N) return phi[n];
if (ansphi[n]) return ansphi[n];
LL tmp;
if (n&1) tmp=(n+1)/2*n;
else tmp=n/2*(n+1);
for (int i=2,j=0;i<=n;i=j+1)
{
j=n/(n/i);
tmp-=sumphi(n/i)*(LL)(j-i+1);
if (j==n) break;
}
ansphi[n]=tmp;
return tmp;
}
LL summu(int n)
{
if (n<=N) return mu[n];
if (ansmu[n]) return ansmu[n];
LL tmp=1;
for (int i=2,j=0;i<=n;i=j+1)
{
j=n/(n/i);
tmp-=summu(n/i)*(LL)(j-i+1);
if (j==n) break;
}
ansmu[n]=tmp;
return tmp;
}
int main()
{
get();
scanf("%d",&T);
while (T--)
{
scanf("%lld",&n);
printf("%lld %lld\n",sumphi(n),summu(n));
}
}