hdu_1286找新朋友(欧拉定理)

题目链接: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


Problem Description
新年快到了,“猪头帮协会”准备搞一个聚会,已经知道现有会员N人,把会员从1到N编号,其中会长的号码是N号,凡是和会长是老朋友的,那么该会员的号码肯定和N有大于1的公约数,否则都是新朋友,现在会长想知道究竟有几个新朋友?请你编程序帮会长计算出来。
 
Input
第一行是测试数据的组数CN(Case number,1<CN<10000),接着有CN行正整数N(1<n<32768),表示会员人数。
 
Output
对于每一个N,输出一行新朋友的人数,这样共有CN行输出。
 
Sample Input
2 25608 24027
 
Sample Output
7680 16016

 题解:求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
",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
",ans);
81     }
82     return 0;
83 }
84 */
原文地址:https://www.cnblogs.com/shanyr/p/5675227.html