Euler's Totient Function: Count of Numbers Less Than n That Are Coprime to n

Words: 228

Introduction

In number theory, for a positive integer n, Euler’s totient function is the number of numbers less than n that are coprime to n. This function is named after its first researcher, Euler (Ruler’so totient function); it is also called Euler’s totient function, the φ function, Euler’s quotient, etc. For example, φ(8)=4, because 1, 3, 5, and 7 are all coprime to 8. The facts in ring theory derived from Euler’s totient function and Lagrange’s theorem constitute the proof of Euler’s theorem.

Properties

$\varphi \left( x\right) =x\left( 1-\dfrac{1}{p_{1}}\right) \left( 1-\dfrac{1}{p_{2}}\right) \ldots \left( 1-\dfrac{1}{p_{n}}\right)$

If n is the k-th power of a prime p

$\varphi \left( n\right) =p^{k}-p^{k-1}$

(because except for multiples of p, all other numbers are coprime to n)
If n is prime, then

$\varphi \left( n\right) = n-1$

These theorems form the basis of computing Euler’s totient function with a sieve.

Algorithm Implementation

Direct Calculation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
int euler(int n){ //返回euler(n)   
     int res=n,a=n;  
     for(int i=2;i*i<=a;i++){  
         if(a%i==0){  
             res=res/i*(i-1);//先进行除法是为了防止中间数据的溢出   
             while(a%i==0) 
             a/=i;  
         }  
     }  
     if(a>1) res=res/a*(a-1);  
     return res;  
}  

Sieve Method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
	long long a[1000020];
	memset(a,0,sizeof(a));
	a[1]=1;
	for(int i=2; i<1000020; i++)
		if(!a[i])
			for(int j=i; j<1000020; j+=i) {
				if(!a[j])
					a[j]=j;
				a[j]=a[j]/i*(i-1);
			}

References:
Euler’s Totient Function - Baidu Baike
Euler’s Totient Function linear sieve
Euler’s Totient Function_Lur ’s acm blog

Loading...