Number theory-Euler function explanation and template

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φ (p-n) = p n-1 (p-1)φ (p-n) = p n-1 (p-1)\varphi (p^{n})=p^{n-1}(p-1)

2. If a is a prime number and a|x, then\varphi (ax)=a\varphi (x)

2. If a and b are relatively prime, then\varphi (ab)=\varphi (a)\varphi (b)

Find the Euler function value of a number:

Decompose a number into prime factors:X = p{_{1}}^{k_{1}}*p{_{2}}^{k_{2}}...p{_{n}}^{k_{n}}

It can be seen from property 1

\varphi (X)=p{_{1}}^{k_{1}-1}*(p{_{1}}-1)*p{_{2}}^{k_{2}-1}*(p{_{2}}-1)...*p{_{n}}^{k_{n}-1}*(p{_{n}}-1)

          =X*(p{_{1}}-1)/p{_{1}}*(p{_{2}}-1)/p{_{2}}...*(p{_{n}}-1)/p{_{n}}

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]];
		}
			
} 

 

Guess you like

Origin blog.csdn.net/qq_44132777/article/details/109673133