VOOZH about

URL: https://www.geeksforgeeks.org/dsa/optimized-euler-totient-function-multiple-evaluations/

⇱ Optimized Euler Totient Function for Multiple Evaluations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Optimized Euler Totient Function for Multiple Evaluations

Last Updated : 23 Jul, 2025

Euler Totient Function (ETF) ?(n) for an input n is 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. 
Examples: 
 

?(5) = 4
gcd(1, 5) is 1, gcd(2, 5) is 1, 
gcd(3, 5) is 1 and gcd(4, 5) is 1

?(6) = 2
gcd(1, 6) is 1 and gcd(5, 6) is 1,


 

Recommended Practice


We have discussed different methods to compute Euler Totient function that work well for single input. In problems where we have to call Euler’s Totient Function many times like 10^5 times, simple solution will result in TLE(Time limit Exceeded). The idea is to use Sieve of Eratosthenes.
Find all prime numbers upto maximum limit say 10^5 using Sieve of Eratosthenes
To compute ?(n), we do following. 
 

  1. Initialize result as n.
  2. Iterate through all primes smaller than or equal to square root of n (This is where it is different from simple methods. Instead of iterating through all numbers less than or equal to square root, we iterate through only primes). Let the current prime number be p. We check if p divides n, if yes, we remove all occurrences of p from n by repeatedly dividing it with n. We also reduce our result by n/p (these many numbers will not have GCD as 1 with n).
  3. Finally we return result.


 

Output: 
 

10
12
30
40
32
60
72
100

Time Complexity: O(MAX*log(MAX)+sqrt(n/log(n)))

Auxiliary Space: O(MAX)


 

Comment