Definition. Euler's Totient Function φ(N) is defined as the number of positive integers≤N that are relatively prime to N, where 1 is counted as being relatively prime to all integers.
The general case of Euler's Totient is φ(n)=nΠp∣n(1−p1)=n(1−p11)(1−p21)...(1−pr1). This is essentially the Inclusion-Exclusion principle.
Code Implementation: Linear Sieve
To calculate a specific totient of n, we could design a trivial O(nlogn) algorithm based on the above formula. However, there exists a sieve algorithm that could calculate totients of number 1 to n in linear time O(n). Below is the code in C++:
C++
// the Euler sieve// bool array: is_prime, int array: prime, phivoidsieve(){
for (int i = 1; i < N; ++i) is_prime[i] = 1;
cnt = 0;
is_prime[1] = 0;
phi[1] = 1;
for (int i = 2; i <= N; ++i) {
if (is_prime[i]) {
prime[++cnt] = i;
phi[i] = i - 1; // for a prime p, phi[p] = p - 1
}
for (int j = 1; j <= cnt && i * prime[j] <= N; ++j) {
is_prime[i * prime[j]] = 0;
if (i % prime[j])
phi[i * prime[j]] = phi[i] * phi[prime[j]];
else {
phi[i * prime[j]] = phi[i] * prime[j];
break;
}
}
}
}
Theorem. Let n be a positive integer, and let a be an integer that is relatively prime to n. Then aφ(n)≡1(modn), where φ(n) is Euler's totient function of n.
Since gcd(a,n)=1, a is invertible modulo n. According to Euler's Theorem, aφ(n)≡1(modn). Therefore a×aφ(n)−1≡1(modn). aφ(n)−1 is a multiplicative inverse of a modulo n.
An informal proof. (need the knowledge of Zn∗, multiplicative group of integers modulo n).
For a∈Zn∗, {r1,r2,...rφ(n)}=(Z/n)∗={ar1,ar2,...arφ(n)}.
Therefore r1r2...rφ(n)≡(ar1)(ar2)...(arφ(n)), which reduces to 1≡aφ(n). This cancellation is allowed since all ri have multiplicative inverses modulo n.