标签:include scan bre ems mes code 数据 names max
一:直接求欧拉函数
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int main(void) { int n; while(~scanf("%d",&n)) { int ans = n; int m = sqrt(n+0.5); for(int i = 2; i <= m; i++) { if(n==1) break; if(n%i==0) { ans = ans/i*(i-1); while(n%i==0) n = n / i ; } } if(n!=1) ans = ans/n*(n-1); printf("%d\n",ans); } return 0; }
二:打表
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int maxn = 100; int euler[maxn]; void Init() { euler[1]=1; for(int i = 2; i <= maxn; i++) euler[i]=i; for(int i = 2; i <= maxn; i++) if(euler[i]==i) for(int j = i; j <= maxn; j+=i) euler[j]=euler[j]/i*(i-1);//先进行除法是为了防止中间数据的溢出 } int main(void) { Init(); for(int i = 1; i <= maxn; i++) { printf("%d %d\n",i,euler[i]); } return 0; }
三:欧拉函数的线性筛法
原理:1:若p是质数,则φ(p)=p-1;
2:若i%p==0,则φ(i*p)=p*φ(i);
3:若i%p!=0,则φ(i*p)=φ(i)*(p-1)
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int maxn = 100; int book[maxn]; int prime[maxn]; int phi[maxn]; int num; void Init() { memset(book, 0, sizeof (book)); phi[1] = 1; book[0] = 1; book[1] = 1; for (int i = 2; i <= maxn; i++) { if (book[i]==0) { prime[num++] = i; phi[i] = i - 1; } for (int j = 0; j < num; j++) { int p = prime[j]; if (i * p > maxn) break; book[i * p] = 1; phi[i * p] = (i % p == 0 ? phi[i] * p : phi[i] * (p - 1)); if (i % p == 0) break; } } } int main(void) { Init(); for(int i = 1; i < maxn; i++) printf("%d %d\n",i,phi[i]); return 0; }
标签:include scan bre ems mes code 数据 names max
原文地址:https://www.cnblogs.com/AC-AC/p/9750070.html