Φ(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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Euler's Totient Function
- Euler's Totient function for all numbers smaller than or equal to n
- Count of elements having Euler's Totient value one less than itself
- Count integers in a range which are divisible by their euler totient value
- Perfect totient number
- Highly Totient Number
- Euler's Four Square Identity
- Euclid Euler Theorem
- Euler's Factorization method
- Number of n digit stepping numbers | Space optimized solution
- Check if a number is Euler Pseudoprime
- Euler zigzag numbers ( Alternating Permutation )
- Euler Method for solving differential equation
- Total nodes traversed in Euler Tour Tree
- Euler's criterion (Check if square root under modulo p exists)
- Predictor-Corrector or Modified-Euler method for solving Differential equation
- Multiple of x closest to n
- Nth number whose sum of digit is multiple of 10
- Find the largest possible k-multiple set
- First N terms whose sum of digits is a multiple of 10
Improved By : Mithun Kumar