Euler function: For any positive integer N, the number of positive integers (including 1) that are less than or equal to N ([1,N]) and relatively prime to N is called the Euler function to N, which is denoted as φ(n). Note: Coprime means that the two have no common factor other than 1.
It is stipulated that φ(1)=1.
The properties of Euler's function:
1. If p is a prime number, then
2. If a is a prime number and a|x, then
2. If a and b are relatively prime, then
Find the Euler function value of a number:
Decompose a number into prime factors:
It can be seen from property 1
So the code is as follows:
int phi(int n) {
int res=n;
for(int i=2;i*i<=n;++i) {
if(n%i==0) res=res/i*(i-1);
while(n%i==0) n/=i;
}
if(n>1) res=res/n*(n-1);
return res;
}
Combined with the sieve method
int phi[maxn];
void init(int n) {
for(int i=1;i<=n;++i) phi[i]=i;
for(int i=2;i<=n;i++) {
if(phi[i]==i){
for(int j=i;j<=n;j+=i) phi[j]=phi[j]/i*(i-1);
}
}
}
Combine with Euler sieve
int phi[maxn];
int prime[maxn],cnt;
int isnp[maxn];
void init(int n) {
phi[1]=1; cnt=0;
for(int i=2;i<=n;i++)
if(!isnp[i])
prime[++cnt]=i,phi[i]=i-1;
for(int j=1;j<=cnt&&i*prime[j]<=n;j++){
isnp[i*prime[j]]=1;
if(i%prime[j]==0) {
phi[prime[j]*i]=phi[i]*prime[j];
break;
}
else phi[prime[j]*i]=phi[i]*phi[prime[j]];
}
}