Φ(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,
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.
- Initialize result as n.
- 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).
- Finally we return result.
10 12 30 40 32 60 72 100
This article is contributed by Abhishek Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Euler's Totient Function
- Euler's Totient function for all numbers smaller than or equal to n
- Probability of Euler's Totient Function in a range [L, R] to be divisible by M
- Check if Euler Totient Function is same for a given number and twice of that number
- Count integers in a range which are divisible by their euler totient value
- Count of elements having Euler's Totient value one less than itself
- Highly Totient Number
- Perfect totient number
- Number of n digit stepping numbers | Space optimized solution
- Print Longest Bitonic subsequence (Space Optimized Approach)
- Euler's criterion (Check if square root under modulo p exists)
- Euler Method for solving differential equation
- Euler's Four Square Identity
- Euclid Euler Theorem
- Total nodes traversed in Euler Tour Tree
- Predictor-Corrector or Modified-Euler method for solving Differential equation
- Euler zigzag numbers ( Alternating Permutation )
- Check if a number is Euler Pseudoprime
- Euler's Factorization method
- Write an Efficient Method to Check if a Number is Multiple of 3
Improved By : Mithun Kumar