(数论)欧拉函数
1~N中与N互质的数的个数成为欧拉函数,记为$\varphi \left ( N \right ) $
根据容斥原理易得:
求一个数的欧拉函数时间复杂度与分解质因数相同,为\(O\left ( \sqrt{N} \right )\)
#include <iostream>
using namespace std;
int eulor(int n) {
int ans = n;
for (int i = 2; i <= x / i; i++) {
if (x % i == 0) {
x /= i;
}
ans = ans / (i - 1) * i;
}
if (x > 1) ans = ans / (x - 1) * x;
return ans;
}
int main() {
cin >> n;
while (n--) {
int x;
cin >> x;
cout << eulor(x) << endl;
}
return 0;
}
接下来考虑求出1~N中所有数的欧拉函数的算法,这里延续了素数筛的思路:
1.由欧拉函数的定义可得\(\varphi \left ( 1 \right ) = 1\),\(\varphi \left ( n \right ) = n - 1\)(当n是质数)
2.考虑每一个合数\(i\times p_{j}\)都会被它的最小质因子\(p_{j}\)筛去,由\(\varphi \left ( n \right )\)的公式可得,当\(p_{j} \mid i\)时,\(\varphi \left ( i\times p_{j} \right ) = \varphi \left ( i \right ) \times p_{j}\),否则\(\varphi \left ( i\times p_{j} \right ) = \varphi \left ( i \right ) \times p_{j} \times \left ( 1 - \frac{1}{p_{j}} \right )=\varphi \left ( i \right ) \times \left ( 1 - p_{j} \right )\)
时间复杂度为\(O\left ( N \right )\)
#include <iostream>
using namespace std;
const int maxn = 1e6 + 10;
int p[maxn], cnt;
int phi[maxn];
bool st[maxn];
int a[maxn];
long long eulor(int n) {
phi[1] = 1;
for (int i = 2; i <= n; i++) {
if (!st[i]) {
p[++cnt] = i;
phi[i] = i - 1;
}
for (int j = 1; p[j] * i <= n; j++) {
st[p[j] * i] = true;
if (i % p[j] == 0) {
phi[p[j] * i] = phi[i] * p[j];
break;
}
phi[p[j] * i] = phi[i] * (p[j] - 1);
}
}
long long res = 0;
for (int i = 1; i <= n; i++)
res += phi[i];
return res;
}
int main() {
int n, t = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
t = max(t, a[i]);
}
eulor(t);
for (int i = 1; i <= n; i++) {
cout << phi[a[i]] << endl;
}
return 0;
}
例题 Visible point
除了(0,1),(1,0),(1,1)这三个点:
一个点是可见的,当且仅当它的横纵坐标互质(不然横纵坐标一定可以约分,被约分后的那个点挡住,只考虑下半边的话,也就是求满足1<x<y<=N且gcd(x,y)=1的点数,只需要求出phi的前缀和减去phi[1]。
总的答案就是3 + 2 * (sum[N] - 1)
#include <iostream>
using namespace std;
const int maxn = 1e5 + 10;
int p[maxn], cnt;
int phi[maxn];
bool st[maxn];
int t[maxn];
long long sum[maxn];
long long eulor(int n) {
phi[1] = 1;
for (int i = 2; i <= n; i++) {
if (!st[i]) {
p[++cnt] = i;
phi[i] = i - 1;
}
for (int j = 1; p[j] <= n / i; j++) {
st[i * p[j]] = true;
if (i % p[j] == 0) {
phi[i * p[j]] = phi[i] * p[j];
break;
}
else phi[i * p[j]] = phi[i] * (p[j] - 1);
}
}
}
int main() {
int n, mx = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> t[i];
mx = max(mx,t[i]);
}
eulor(mx);
for (int i = 1; i <= mx; i++)
sum[i] = sum[i - 1] + phi[i];
for (int i = 1; i <= n; i++)
printf("%d %d %lld\n", i, t[i], 3 + 2 * (sum[t[i]] - 1));
return 0;
}