如果一个数
i
i
i 是质数,那么欧拉函数
ϕ
(
i
)
=
i
−
1
\phi(i) = i - 1
ϕ(i)=i−1;
if (i % primes[j] == 0):
ϕ
(
i
)
=
i
(
1
−
1
P
1
)
⋯
(
1
−
1
P
j
)
⋯
(
1
−
1
P
k
)
\phi(i) = i(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_j})\cdots(1-\frac{1}{P_k})
ϕ(i)=i(1−P11)⋯(1−Pj1)⋯(1−Pk1),//
P
j
P_j
Pj是i的一个质因子,直接用欧拉函数的公式,同时
P
j
P_j
Pj也是
P
j
×
i
P_j \times i
Pj×i的质因子;
ϕ
(
P
j
i
)
=
P
j
i
(
1
−
1
P
1
)
⋯
(
1
−
1
P
j
)
⋯
(
1
−
1
P
k
)
=
P
j
ϕ
(
i
)
\phi(P_j i) = P_ji(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_j})\cdots(1-\frac{1}{P_k}) = P_j\phi(i)
ϕ(Pji)=Pji(1−P11)⋯(1−Pj1)⋯(1−Pk1)=Pjϕ(i);
if (i % primes[j] != 0:
ϕ
(
i
)
=
i
(
1
−
1
P
1
)
⋯
(
1
−
1
P
k
)
\phi(i) = i(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_k})
ϕ(i)=i(1−P11)⋯(1−Pk1),//
P
j
P_j
Pj不是i的质因子,但是
P
j
×
i
P_j \times i
Pj×i的质因子;
ϕ
(
P
j
i
)
=
P
j
i
(
1
−
1
P
1
)
⋯
(
1
−
1
P
k
)
(
1
−
1
P
j
)
=
P
j
ϕ
(
i
)
(
1
−
1
P
j
)
=
(
P
j
−
1
)
ϕ
(
i
)
\phi(P_ji) = P_ji(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_k})(1-\frac{1}{P_j}) = P_j\phi(i)(1-\frac{1}{P_j}) = (P_j - 1)\phi(i)
ϕ(Pji)=Pji(1−P11)⋯(1−Pk1)(1−Pj1)=Pjϕ(i)(1−Pj1)=(Pj−1)ϕ(i);
Code:
#include<iostream>usingnamespace std;constint N =1e6+10;int primes[N], cnt;int phi[N];bool st[N];longlongeuler(int n){
phi[1]=1;//1~1中和1互质的数只有1for(int i =2; i <= n; i ++){if(!st[i]){
primes[cnt ++]= i;
phi[i]= i -1;//质数i的欧拉函数为i-1}for(int j =0; primes[j]<= n / i; j ++){
st[primes[j]* i]=true;if(i % primes[j]==0){
phi[primes[j]* i]= primes[j]* phi[i];break;}
phi[primes[j]* i]=(primes[j]-1)* phi[i];}}longlong res =0;for(int i =1; i <= n; i ++)
res += phi[i];return res;}intmain(){int n;
cin >> n;
cout <<euler(n)<< endl;return0;}
Tips:
欧拉筛模板:
int primes[N], cnt;int phi[N];bool st[N];voideuler(int n){
phi[1]=1;for(int i =2; i <= n; i ++){if(!st[i]){
primes[cnt ++]= i;
phi[i]= i -1;}for(int j =0; primes[j]<= n / i; j ++){
st[primes[j]* i]=true;if(i % primes[j]==0){
phi[primes[j]* i]= primes[j]* phi[i];break;}
phi[primes[j]* i]=(primes[j]-1)* phi[i];}}}
Issue:Thinking:在线性筛质数下同时把欧拉函数给筛出来;如果一个数 iii 是质数,那么欧拉函数 ϕ(i)=i−1\phi(i) = i - 1ϕ(i)=i−1;if (i % primes[j] == 0):ϕ(i)=i(1−1P1)⋯(1−1Pj)⋯(1−1Pk)\phi(i) = i(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_j})\cdots(1-\frac{1}{P_k})ϕ(i)=i(1−P11)⋯(1−Pj1)⋯(1−Pk1),/