Definition#
The Euler's Totient Function is a function that counts the number of positive integers less than or equal to that are coprime to . It is denoted as .
example
, (1)
, (1, 2)
, (1, 3)
, (1, 2, 3, 4)
, (1, 5)
Formula#
Conclusion#
Assuming the prime factorization of is ( is a prime factor), the Euler's Totient Function can be calculated using the formula:
Derivation#
First, if a number is coprime to , it means that they do not have any common prime factors, i.e., cannot have prime factors such as , , ..., .
So, the number of integers in the range that have as a prime factor is .
Similarly, for each prime factor , the number of integers in the range that have as a prime factor is .
Obviously, the number of integers without the prime factor is .
By adding the numbers that were subtracted repeatedly, we can use the principle of inclusion-exclusion to obtain:
=n(1- \cfrac{1}{p_1}) \times (1-\cfrac{1}{p_2})...(1-\cfrac{1}{p_m})$$
Naive Algorithm#
1#
According to the definition, directly enumerate the number of integers in the range that are coprime to and have the greatest common divisor of 1.
for(int i=1; i<=n; i++)
ans += gcd(n, i)==1;
2#
According to the formula
Loop through the prime factors and calculate ans=ans*(1-1/pi), i.e., ans-= ans/pi
ans = n;
for(int i=2; i*i<=n; i++) {
if(n%i==0) {
ans -= ans/i;
while(n%i==0) n/=i;
}
}
if(n>1) ans -= ans/n;
Sieve Method#
Eratosthenes Sieve Method#
According to the definition of the Euler's Totient Function,
The principle of the Eratosthenes Sieve Method is to sieve all multiples of the prime number , indicating that has a prime factor , so it can be calculated using the formula mentioned above.
- First, phi[x] = x
- For each multiple j of the prime number , phi[j] *= (1-1/pi), which means phi[j] -= phi[j]/pi
- If for some i, phi[i] != i, it means it has been sieved before and is a composite number
void sieve(int mx) {
for(int i=1; i<=mx; i++)
phi[i] = i;
for(int i=2; i<=mx; i++) {
if(phi[i] != i) continue;
for(int j=i; j<=mx; j+=i)
phi[j] -= phi[j]/i;
}
}
Euler's Sieve Method#
For a prime number , there are two cases to consider:
- If it is a prime factor of x, then for , pi has already been calculated in the Euler's Totient Function , so we have:
- If it is not a prime factor of x, then for , there is an additional prime factor, so we have:
Combining with the Euler's Sieve Method, we can obtain the code to calculate phi[x].
void sieve(int mx) {
phi[1] = 1;
for(int i=2; i<=mx; i++) {
if(!notPrime[i]) {
p[++last] = i;
phi[i] = i-1;
}
for(int j=1; j<=last; j++) {
int t = i * p[j];
if(t>=mx) break;
notPrime[t] = true;
if(i % p[j]==0) {
phi[t] = phi[i] * p[j];
break;
} else
phi[t]= phi[i] * (p[j]-1);
}
}
}