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)
C++
#include <bits/stdc++.h>#define int long longusing 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:
C++
#include <bits/stdc++.h>#define int long longusing 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:
C++
#include <bits/stdc++.h>#define int long longusing 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;
}