2022.07.27 笔记
2022.07.27 笔记
欧拉函数
定义:
若在算数的基本定理中,$N = p_1^{a_1} p_2^{a_2} \dots p_m^{a_m}$,则: $$ \begin{aligned} \phi(N) &= N \times \frac {p_1 - 1} {p_1} \times \frac {p_2 - 1} {p2} \times \dots \times \frac {p_m - 1} {p_m}\\ &= (p_1 - 1) \times (p_2 - 1) \times \dots \times (p_m - 1) \end{aligned} $$ ### 例子: > $$ > \begin{aligned} > \phi(30) &= 30 \times \frac {2 - 1} {2} \times \frac {3 - 1} {3} \times \frac {5 - 1} {5} \\ > &= (2 - 1) \times (3 - 1) \times (4 - 1) \\ > &= 1 \times 2 \times 4 \\ > &= 8 \\ > \end{aligned} > $$ code:
int phi(int x) { int res = x; for (int i = 2; i <= x / i; i ++ ) if (x % i == 0) { res = res / i * (i - 1); while (x % i == 0) x /= i; } if (x > 1) res = res / x * (x - 1); return res; }AcWing(873)
#include <bits/stdc++.h> #define int long long using namespace std; int phi(int x) { int res = x; for (int i = 2; i <= x / i; i ++ ) { if (x % i == 0) { res = res / i * (i - 1); while (x % i == 0) x /= i; } } if (x > 1) res = res / x * (x - 1); return res; } signed main() { int n; cin >> n; while (n -- ) { int x; cin >> x; cout << phi(x) << endl; } }
欧拉函数求和
1.暴力(会T)
code:
#include <bits/stdc++.h> #define int long long using namespace std; int phi(int x) { int res = x; for (int i = 2; i <= x / i; i ++ ) if (x % i == 0) { res = res / i * (i - 1); while (x % i == 0) x /= i; } if (x > 1) res = res / x * (x - 1); return res; } signed main() { int n; cin >> n; int ans = 0; for (int i = 1; i <= n; i ++ ) { ans += phi(i); } cout << ans; return 0; }2.线性筛(AC)
code:
#include <bits/stdc++.h> #define int long long using namespace std; const int N = 1e6 + 10; int n, cnt, p[N], phi[N]; bool vis[N]; int get(int n) { phi[1] = 1; for (int i = 2; i <= n; i ++ ) { if (!vis[i]) { p[ ++ cnt] = i; phi[i] = i - 1; } for (int j = 1; p[j] <= n / i; j ++ ) { vis[p[j] * i] = 1; if (i % p[j] == 0) { phi[p[j] * i] = phi[i] * p[j]; break; } else phi[p[j] * i] = phi[i] * (p[j] - 1); } } int res = 0; for (int i = 1; i <= n; i ++ ) res += phi[i]; return res; } signed main() { cin >> n; cout << get(n) << endl; return 0; }