欧拉函数
欧拉函数的定义:
N
=
p
1
a
1
p
2
a
2
.
.
.
p
m
a
m
N = p_1^{a_1} p_2^{a_2}...p_m^{a_m}
N=p1a1p2a2...pmam,则
欧
拉
(
N
)
=
N
∗
p
1
−
1
p
1
∗
p
2
−
1
p
2
∗
.
.
.
∗
p
m
−
1
p
m
欧拉(N) = N * \frac{p_1-1}{p_1}* \frac{p_2-1}{p_2}*...* \frac{p_m-1}{p_m}
欧拉(N)=N∗p1p1−1∗p2p2−1∗...∗pmpm−1
意义是与N互质的数的个数。
质数p的欧拉函数值为p-1
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
for(int i = 0; i < n; ++i){
int a;
cin >> a;
int ans = a;
for(int i = 2; i <= a / i; ++i){
if(a % i == 0) ans = ans / i * (i - 1);
while(a % i == 0) a /= i;
}
if (a > 1) ans = ans / a * (a - 1);
cout << ans << endl;
}
return 0;
}
筛法求欧拉函数
- 当i为质数时,phi[i] = i - 1;
- 当i不为质数时
- 当 i % prime[j] == 0 时 :
- phi[i * prime[j]] = prime[j] * phi[i];
- 当 i % prime[j] != 0 时:
- phi[i * prime[j]] = (prime[j] - 1) * ph[i];
- 当 i % prime[j] == 0 时 :
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
int prime[N], idx = 0, phi[N];
bool st[N];
typedef long long LL;
LL erlou(int n){
phi[1] = 1;
for(int i = 2; i <= n; ++i){
if(!st[i]){
prime[idx++] = i;
phi[i] = i - 1;
}
for(int j = 0; prime[j] <= n / i; ++j){
st[prime[j] * i] = true;
if(i % prime[j] == 0){
phi[prime[j] * i] = phi[i] * prime[j];
break;
}
phi[i*prime[j]] = phi[i] * (prime[j] - 1);
}
}
LL res = 0;
for(int i = 1; i <= n; ++i) res += phi[i];
return res;
}
int main(){
int n;
cin >> n;
cout << erlou(n);
return 0;
}