标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1286
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10969 Accepted Submission(s): 5818
题解:求1~n-1中和n互质的数的个数,其实就是求n 的欧拉函数,可以直接带入公式F(n) = n*(1-1/p1)*(1-1/p2)……*(1-1/pk) (pi是n 质因数分解的每个质因数)
1 //欧拉函数 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 const int N = 32770; 7 int ans[N]; 8 bool pri[N]; 9 void init() 10 { 11 for(int i = 1; i < N; i++) ans[i] = i; 12 pri[0] = pri[1] = 1; 13 for(int i = 2; i < N; i++){ 14 if(!pri[i]){ 15 ans[i]=i-1; 16 for(int j = i+i; j < N; j+=i){ 17 pri[j] = 1; 18 ans[j] = ans[j]/i*(i-1); 19 } 20 } 21 } 22 return; 23 } 24 int main() 25 { 26 int T; 27 scanf("%d",&T); 28 init(); 29 while(T--) 30 { 31 int n; 32 scanf("%d",&n); 33 printf("%d\n",ans[n]); 34 } 35 return 0; 36 } 37 38 /* 39 40 //求欧拉函数 41 #include<cstdio> 42 #include<cstring> 43 #include<algorithm> 44 #include<vector> 45 using namespace std; 46 const int N = 33000; 47 int mp[N][50]; 48 int cnt[N]; 49 bool pri[N]; 50 void init() 51 { 52 memset(cnt,0,sizeof(cnt)); 53 memset(mp,0,sizeof(mp)); 54 pri[0] = pri[1] = 1; 55 for(int i = 2; i < N; i++) 56 { 57 if(!pri[i]){ 58 mp[i][0] = i; 59 cnt[i] = 1; 60 for(int j = i+i; j < N; j+=i){ 61 pri[j] = 1; 62 mp[j][cnt[j]++] = i; 63 } 64 } 65 } 66 } 67 int main() 68 { 69 int T; 70 scanf("%d",&T); 71 init(); 72 while(T--) 73 { 74 int n; 75 scanf("%d",&n); 76 int ans = n; 77 for(int i = 0; i < cnt[n]; i++){ 78 ans = ans/mp[n][i]*(mp[n][i]-1); 79 } 80 printf("%d\n",ans); 81 } 82 return 0; 83 } 84 */
标签:
原文地址:http://www.cnblogs.com/shanyr/p/5675227.html