3944: Sum
Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 4930 Solved: 1313
[Submit][Status][Discuss]
Description
Input
一共T+1行
第1行为数据组数T(T<=10)
第2~T+1行每行一个非负整数N,代表一组询问
Output
一共T行,每行两个用空格分隔的数ans1,ans2
Sample Input
6
1
2
8
13
30
2333
Sample Output
1 1
2 0
22 -2
58 -3
278 -3
1655470 2
/* 就相当于111112222222333333333每个数都有相同的一坨,然后只算出一坨的第一个数,乘个他的次数,直接跳到下一坨 */ #include<iostream> #include<cstdio> #include<cstring> #include<map> #define maxn 5000005 #define N 5000000 using namespace std; int p[maxn],mu[maxn],cnt; long long phi[maxn]; bool vis[maxn]; void prepare(){ memset(vis,0,sizeof(vis)); phi[1]=1;mu[1]=1; for(int i=2;i<=N;i++){ if(!vis[i])p[++cnt]=i,phi[i]=i-1,mu[i]=-1; for(int j=1;j<=cnt&&i*p[j]<=N;j++){ vis[i*p[j]]=1; if(i%p[j]==0){ phi[i*p[j]]=phi[i]*p[j]; mu[p[j]*i]=0;break; } phi[i*p[j]]=phi[i]*phi[p[j]]; mu[i*p[j]]=-mu[i]; } } for(int i=1;i<=N;i++)phi[i]+=phi[i-1],mu[i]+=mu[i-1]; } map<long long,long long>lst_phi; map<long long,int>lst_mu; long long sum_phi(long long n){ if(n<=N)return phi[n]; if(lst_phi[n]!=0)return lst_phi[n]; long long res=n*(n+1)/2; for(long long i=2,nxt;i<=n;i=nxt+1){ nxt=n/(n/i); res-=sum_phi(n/i)*(nxt-i+1); } return lst_phi[n]=res; } int sum_mu(long long n){ if(n<=N)return mu[n]; if(lst_mu[n]!=0)return lst_mu[n]; int res=1; for(long long i=2,nxt;i<=n;i=nxt+1){ nxt=n/(n/i); res-=sum_mu(n/i)*(nxt-i+1); } return lst_mu[n]=res; } int main(){ freopen("Cola.txt","r",stdin); prepare(); int Q;scanf("%d",&Q); while(Q--){ int n;scanf("%d",&n); cout<<sum_phi(n)<<‘ ‘<<sum_mu(n)<<endl; } }
原文地址:https://www.cnblogs.com/thmyl/p/8261674.html
时间: 2024-10-09 07:20:34