欧拉函数

1、分解质因数

 1 /*
 2 f(n) : 1 - n 中与n互质的个数(gcd(a, b) = 1)
 3 n = p1^a1.p2^a2...pn^an
 4 f(n) = n * (1 - 1/p1)(1 - 1/p2)...(1 - 1/pn)
 5 */
 6 #include <bits/stdc++.h>
 7 using namespace std;
 8 
 9 int div_ola(int x){
10     int res = x;
11     for(int i = 2; i <= x / i; ++i){
12         if(x % i == 0){
13             res = res / i * (i - 1);
14             while(x % i == 0) x /= i;
15         }
16     }
17     if(x > 1) res = res / x * (x - 1);
18     return res;
19 }
20 
21 signed main(){
22     int n;
23     cin >> n;
24     cout << div_ola(n);
25 
26     return 0;
27 }

2、筛法

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int N = 1e5 + 10;
 5 int cnt, p[N], st[N], e[N];
 6 
 7 void div_ola(int n){
 8     e[1] = 1;
 9     for(int i = 2; i <= n; ++i){
10         if(!st[i]){
11             p[cnt++] = i;
12             e[i] = i - 1;
13         }
14         for(int j = 0; p[j] <= n / i; ++j){
15             int t = p[j] * i;
16             st[t] = true;
17             if(i % p[j] == 0){
18                 e[t] = e[i] * p[j];
19                 break;
20             }
21             e[t] = e[i] * (p[j] - 1);
22         }
23     }
24 }
25 
26 signed main(){
27     div_ola(100);
28     for(int i = 1; i <= 100; ++i) cout << e[i] << " ";
29 
30     return 0;
31 }

 

posted @ 2022-04-04 14:33  std&ice  阅读(98)  评论(0编辑  收藏  举报