Φ(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.
- Euler's Totient Function
- Euler's Totient function for all numbers smaller than or equal to n
- How to return multiple values from a function in C or C++?
- How can I return multiple values from a function?
- A Space Optimized Solution of LCS
- Vertical Sum in Binary Tree | Set 2 (Space Optimized)
- A Space Optimized DP solution for 0-1 Knapsack Problem
- Optimized Naive Algorithm for Pattern Searching
- Longest Common Substring (Space optimized DP solution)
- Word Wrap problem ( Space optimized solution )
- Project Euler
- Dial's Algorithm (Optimized Dijkstra for small range weights)
- Printing Matrix Chain Multiplication (A Space Optimized Solution)
- Euler Tour of Tree
- Euclid Euler Theorem