![]() |
VOOZH | about |
Euler's Totient function φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1.
Example:
Input: n = 5
Output:
Totient of 1 is 1
Totient of 2 is 1
Totient of 3 is 2
Totient of 4 is 2
Totient of 5 is 4
Explanation:
1 has 1 coprime number → φ(1) = 1
2 has 1 coprime number (1) → φ(2) = 1
3 has 2 coprime numbers (1,2) → φ(3) = 2
4 has 2 coprime numbers (1,3) → φ(4) = 2
5 has 4 coprime numbers (1,2,3,4) → φ(5) = 4
Input: n = 12
Output:
Totient of 1 is 1
Totient of 2 is 1
Totient of 3 is 2
Totient of 4 is 2
Totient of 5 is 4
Totient of 6 is 2
Totient of 7 is 6
Totient of 8 is 4
Totient of 9 is 6
Totient of 10 is 4
Totient of 11 is 10
Totient of 12 is 4
Explanation:
1 has 1 coprime number → φ(1) = 1 → {1}
2 has 1 coprime number → φ(2) = 1 → {1}
3 has 2 coprime numbers → φ(3) = 2 → {1,2}
4 has 2 coprime numbers → φ(4) = 2 → {1,3}
5 has 4 coprime numbers → φ(5) = 4 → {1,2,3,4}
6 has 2 coprime numbers → φ(6) = 2 → {1,5}
7 has 6 coprime numbers → φ(7) = 6 → {1,2,3,4,5,6}
8 has 4 coprime numbers → φ(8) = 4 → {1,3,5,7}
9 has 6 coprime numbers → φ(9) = 6 → {1,2,4,5,7,8}
10 has 4 coprime numbers → φ(10) = 4 → {1,3,7,9}
11 has 10 coprime numbers → φ(11) = 10 → {1,2,3,4,5,6,7,8,9,10}
12 has 4 coprime numbers → φ(12) = 4 → {1,5,7,11}
Table of Content
A simple solution is to iterate through all numbers from 1 to n-1 and count numbers with gcd with n as 1. Below is the implementation of the simple method to compute Euler's Totient function for an input integer n.
10
An Efficient Solution is to use an idea similar to the Sieve of Eratosthenes to precompute all values. The method is based on below product formula.
Below is the complete algorithm:
Step 1. Create an array phi[1..n] to store φ values of all numbers from 1 to n.
Step 2. Initialize all values such that phi[i] stores i. This initialization serves two purposes.
Step 3. Run a loop for p = 2 to n
Step 4. Run a loop from i = 1 to n and print all Phi[i] values.
Totient of 1 is 1 Totient of 2 is 1 Totient of 3 is 2 Totient of 4 is 2 Totient of 5 is 4 Totient of 6 is 2 Totient of 7 is 6 Totient of 8 is 4 Totient of 9 is 6 Totient of 10 is 4 Totient of 11 is 10...
Time Complexity: O(n log(log n))
Auxiliary Space: O(n)
The sieve-based solution is useful when we have a large number of queries for computing the totient function.
For numbers upto n, we can use Prime Factorization.
This approach computes φ(n) using prime factorization instead of iterating over all numbers.
For example, φ(12) = { (2^(2-1)) x (2-1) } x { (3^(1-1)) x (3-1) } =4
Note that φ(n) = n - 1 if n is prime.
Totient of 1 is: 1 Totient of 2 is: 1 Totient of 3 is: 2 Totient of 4 is: 2 Totient of 5 is: 4 Totient of 6 is: 2 Totient of 7 is: 6 Totient of 8 is: 4 Totient of 9 is: 6 Totient of 10 is: 4 Totient o...