![]() |
VOOZH | about |
Euler Totient Function or Phi-function for 'n', gives the count of integers in range '1' to 'n' that are co-prime to 'n'. It is denoted by .
👁 etfdrawio
For example the below table shows the ETF value of first 15 positive integers:
{prime factorizing n}
The above code shows that we can calculate the ETF value for 'n' in O(\sqrt{n} ), If we want to calculate ETF value for each integer from 1 to n then it will take us O(n\sqrt{n}) .
Can we optimize this time complexity? YES we can, using precomputation similar to Sieve of Eratosthenes we can reduce the time complexity to O(n*log(log n)) as shown in below code:
ETF is considered to be an advance topic for competitive programming which requires a good understanding of mathematics and its problem difficulty ranges from medium to hard. For a problem we can try to think towards ETF in the following scenarios:
- GCD and LCM based problems
- Use of Chinese Remainder Theorem
- Use of Fermat's Little Theorem
- Problem requires calcuation of Large Exponentiations such as
Note: It is not necessary that all the above type of problems can be solved using Euler Totient Function, we can try to think in ETF's direction if above jargons are used in the problem statement.
Euler's Totient Theorem states that if a and n are coprime (gcd(a, n) = 1), then . This theorem is used to find the remainder of a number raised to a large power modulo n efficiently. Competitive programming problems often require solving such congruence relations.
You may encounter problems that require counting the number of pairs (a, b) such that 1 ≤ a, b ≤ n and gcd(a, b) = 1. The Euler Totient function can be used here to calculate and then determine the count of coprime pairs.
In dynamic programming (DP) problems, you might use as a state in your DP table when solving combinatorial or counting problems involving modular arithmetic.