首页 > 代码库 > HDU - 1286 找新朋友

HDU - 1286 找新朋友

版本一:

技术分享
 1 #include<bits/stdc++.h>
 2 #define IO ios_base::sync_with_stdio(0);cin.tie(0);
 3 using namespace std;
 4 int prime[32770], phi[32770];
 5 int main()
 6 {IO;
 7     int T;
 8     cin >> T;
 9     while(T --){
10         int n;
11         cin >> n;
12         memset(prime, 1, sizeof(prime));
13         prime[0] = 0;
14         prime[1] = 0;
15         for(int i = 2; i * i <= n; i ++){
16             if(prime[i]){
17                 for(int j = i + i; j <= n; j += i){
18                     prime[j] = 0;
19                 }
20             }
21         }//找到所有n以内的素数
22         for(int i = 1; i <= n; i ++)
23             phi[i] = i;
24         for(int i = 2; i <= n; i ++){
25             if(prime[i]){
26                 for(int j = i; j <= n; j += i){
27                     phi[j] = phi[j] / i * (i - 1);
28                 }
29             }
30         }//求出n以内所有数的欧拉值
31         cout << phi[n] << endl;
32     }
33 }
View Code

版本二:

技术分享
 1 #include<bits/stdc++.h>
 2 #define IO ios_base::sync_with_stdio(0);cin.tie(0);
 3 using namespace std;
 4 int prime[32770], u[32770], phi[32770];
 5 int main()
 6 {IO;
 7     int T;
 8     cin >> T;
 9     while(T --){
10         int n;
11         cin >> n;
12         int sum = 0;
13         phi[1] = 1;
14         memset(u, 1, sizeof(u));
15         for(int i = 2; i <= n; i ++){
16             if(u[i]){
17                 prime[++ sum] = i;
18                 phi[i] = i - 1;
19             }
20             for(int j = 1; j <= sum; j ++){
21                 if(i * prime[j] > n) break;
22                 u[i * prime[j]] = 0;
23                 if(i % prime[j]){
24                    phi[i * prime[j]] = phi[i] * (prime[j] - 1);
25                 }
26                 else{
27                     phi[i * prime[j]] = phi[i] * prime[j];
28                 }
29             }
30         }
31         cout << phi[n] << endl;
32     }
33 }
View Code

 

HDU - 1286 找新朋友