Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Optimized Euler Totient Function for Multiple Evaluations
Next article icon

Optimized Euler Totient Function for Multiple Evaluations

Last Updated : 17 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
Euler Totient Function
Try It!


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.


 

C++
// C++ program to efficiently compute values // of euler totient function for multiple inputs. #include <bits/stdc++.h> using namespace std;  #define ll long long const int MAX = 100001;  // Stores prime numbers upto MAX - 1 values vector<ll> p;  // Finds prime numbers upto MAX-1 and // stores them in vector p void sieve() {     ll isPrime[MAX+1];      for (ll i = 2; i<= MAX; i++)     {         // if prime[i] is not marked before         if (isPrime[i] == 0)         {             // fill vector for every newly             // encountered prime             p.push_back(i);              // run this loop till square root of MAX,             // mark the index i * j as not prime             for (ll j = 2; i * j<= MAX; j++)                 isPrime[i * j]= 1;         }     } }  // function to find totient of n ll phi(ll n) {     ll res = n;      // this loop runs sqrt(n / ln(n)) times     for (ll i=0; p[i]*p[i] <= n; i++)     {         if (n % p[i]== 0)         {             // subtract multiples of p[i] from r             res -= (res / p[i]);              // Remove all occurrences of p[i] in n             while (n % p[i]== 0)                n /= p[i];         }     }      // when n has prime factor greater     // than sqrt(n)     if (n > 1)        res -= (res / n);      return res; }  // Driver code int main() {     // preprocess all prime numbers upto 10 ^ 5     sieve();     cout << phi(11) << "\n";     cout << phi(21) << "\n";     cout << phi(31) << "\n";     cout << phi(41) << "\n";     cout << phi(51) << "\n";     cout << phi(61) << "\n";     cout << phi(91) << "\n";     cout << phi(101) << "\n";     return 0; } 
Java
// Java program to efficiently compute values  // of euler totient function for multiple inputs.  import java.util.*;   class GFG{  static int MAX = 100001;   // Stores prime numbers upto MAX - 1 values  static ArrayList<Integer> p = new ArrayList<Integer>();  // Finds prime numbers upto MAX-1 and  // stores them in vector p  static void sieve()  {      int[] isPrime=new int[MAX+1];       for (int i = 2; i<= MAX; i++)      {          // if prime[i] is not marked before          if (isPrime[i] == 0)          {              // fill vector for every newly              // encountered prime              p.add(i);               // run this loop till square root of MAX,              // mark the index i * j as not prime              for (int j = 2; i * j<= MAX; j++)                  isPrime[i * j]= 1;          }      }  }   // function to find totient of n  static int phi(int n)  {      int res = n;       // this loop runs sqrt(n / ln(n)) times      for (int i=0; p.get(i)*p.get(i) <= n; i++)      {          if (n % p.get(i)== 0)          {              // subtract multiples of p[i] from r              res -= (res / p.get(i));               // Remove all occurrences of p[i] in n              while (n % p.get(i)== 0)              n /= p.get(i);          }      }       // when n has prime factor greater      // than sqrt(n)      if (n > 1)      res -= (res / n);       return res;  }   // Driver code  public static void main(String[] args)  {      // preprocess all prime numbers upto 10 ^ 5      sieve();      System.out.println(phi(11));      System.out.println(phi(21));      System.out.println(phi(31));      System.out.println(phi(41));      System.out.println(phi(51));      System.out.println(phi(61));      System.out.println(phi(91));      System.out.println(phi(101));    }  } // this code is contributed by mits 
Python3
# Python3 program to efficiently compute values  # of euler totient function for multiple inputs.   MAX = 100001;   # Stores prime numbers upto MAX - 1 values  p = [];  # Finds prime numbers upto MAX-1 and  # stores them in vector p  def sieve():       isPrime = [0] * (MAX + 1);       for i in range(2, MAX + 1):                   # if prime[i] is not marked before          if (isPrime[i] == 0):                           # fill vector for every newly              # encountered prime              p.append(i);               # run this loop till square root of MAX,              # mark the index i * j as not prime             j = 2;             while (i * j <= MAX):                  isPrime[i * j]= 1;                 j += 1;  # function to find totient of n  def phi(n):      res = n;       # this loop runs sqrt(n / ln(n)) times     i = 0;     while (p[i] * p[i] <= n):          if (n % p[i]== 0):                           # subtract multiples of p[i] from r              res -= int(res / p[i]);               # Remove all occurrences of p[i] in n              while (n % p[i]== 0):                 n = int(n / p[i]);          i += 1;      # when n has prime factor greater      # than sqrt(n)      if (n > 1):         res -= int(res / n);       return res;   # Driver code   # preprocess all prime numbers upto 10 ^ 5  sieve();  print(phi(11));  print(phi(21));  print(phi(31));  print(phi(41));  print(phi(51));  print(phi(61));  print(phi(91));  print(phi(101));   # This code is contributed by mits 
C#
// C# program to efficiently compute values  // of euler totient function for multiple inputs.  using System; using System.Collections; class GFG{  static int MAX = 100001;   // Stores prime numbers upto MAX - 1 values  static ArrayList p = new ArrayList();  // Finds prime numbers upto MAX-1 and  // stores them in vector p  static void sieve()  {      int[] isPrime=new int[MAX+1];       for (int i = 2; i<= MAX; i++)      {          // if prime[i] is not marked before          if (isPrime[i] == 0)          {              // fill vector for every newly              // encountered prime              p.Add(i);               // run this loop till square root of MAX,              // mark the index i * j as not prime              for (int j = 2; i * j<= MAX; j++)                  isPrime[i * j]= 1;          }      }  }   // function to find totient of n  static int phi(int n)  {      int res = n;       // this loop runs sqrt(n / ln(n)) times      for (int i=0; (int)p[i]*(int)p[i] <= n; i++)      {          if (n % (int)p[i]== 0)          {              // subtract multiples of p[i] from r              res -= (res / (int)p[i]);               // Remove all occurrences of p[i] in n              while (n % (int)p[i]== 0)              n /= (int)p[i];          }      }       // when n has prime factor greater      // than sqrt(n)      if (n > 1)      res -= (res / n);       return res;  }   // Driver code  static void Main()  {      // preprocess all prime numbers upto 10 ^ 5      sieve();      Console.WriteLine(phi(11));      Console.WriteLine(phi(21));      Console.WriteLine(phi(31));      Console.WriteLine(phi(41));      Console.WriteLine(phi(51));      Console.WriteLine(phi(61));      Console.WriteLine(phi(91));      Console.WriteLine(phi(101));   }  } // this code is contributed by mits 
PHP
<?php // PHP program to efficiently compute values  // of euler totient function for multiple inputs.   $MAX = 100001;   // Stores prime numbers upto MAX - 1 values  $p = array();  // Finds prime numbers upto MAX-1 and  // stores them in vector p  function sieve()  {     global $MAX,$p;     $isPrime=array_fill(0,$MAX+1,0);       for ($i = 2; $i<= $MAX; $i++)      {          // if prime[i] is not marked before          if ($isPrime[$i] == 0)          {              // fill vector for every newly              // encountered prime              array_push($p,$i);               // run this loop till square root of MAX,              // mark the index i * j as not prime              for ($j = 2; $i * $j<= $MAX; $j++)                  $isPrime[$i * $j]= 1;          }      }  }   // function to find totient of n  function phi($n)  {     global $p;     $res = $n;       // this loop runs sqrt(n / ln(n)) times      for ($i=0; $p[$i]*$p[$i] <= $n; $i++)      {          if ($n % $p[$i]== 0)          {              // subtract multiples of p[i] from r              $res -= (int)($res / $p[$i]);               // Remove all occurrences of p[i] in n              while ($n % $p[$i]== 0)              $n = (int)($n/$p[$i]);          }      }       // when n has prime factor greater      // than sqrt(n)      if ($n > 1)      $res -= (int)($res / $n);       return $res;  }   // Driver code        // preprocess all prime numbers upto 10 ^ 5      sieve();      print(phi(11)."\n");      print(phi(21)."\n");      print(phi(31)."\n");      print(phi(41)."\n");      print(phi(51)."\n");      print(phi(61)."\n");      print(phi(91)."\n");      print(phi(101)."\n");   // this code is contributed by mits ?> 
JavaScript
<script>  // Javascript program to efficiently compute values  // of euler totient function for multiple inputs.   var MAX = 100001;   // Stores prime numbers upto MAX - 1 values  var p = [];  // Finds prime numbers upto MAX-1 and  // stores them in vector p  function sieve()  {      var isPrime = Array(MAX+1).fill(0);      for (var i = 2; i<= MAX; i++)      {          // if prime[i] is not marked before          if (isPrime[i] == 0)          {              // fill vector for every newly              // encountered prime              p.push(i);               // run this loop till square root of MAX,              // mark the index i * j as not prime              for (var j = 2; i * j<= MAX; j++)                  isPrime[i * j]= 1;          }      }  }   // function to find totient of n  function phi(n)  {      var res = n;       // this loop runs sqrt(n / ln(n)) times      for (var i=0; p[i]*p[i] <= n; i++)      {          if (n % p[i]== 0)          {              // subtract multiples of p[i] from r              res -= parseInt(res / p[i]);               // Remove all occurrences of p[i] in n              while (n % p[i]== 0)              n = parseInt(n/p[i]);          }      }       // when n has prime factor greater      // than sqrt(n)      if (n > 1)      res -= parseInt(res / n);       return res;  }   // Driver code  // preprocess all prime numbers upto 10 ^ 5  sieve();  document.write(phi(11)+ "<br>");  document.write(phi(21)+ "<br>");  document.write(phi(31)+ "<br>");  document.write(phi(41)+ "<br>");  document.write(phi(51)+ "<br>");  document.write(phi(61)+ "<br>");  document.write(phi(91)+ "<br>");  document.write(phi(101)+ "<br>");   // This code is contributed by rutvik_56. </script> 

Output: 
 

10 12 30 40 32 60 72 100

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

Auxiliary Space: O(MAX)

 


Next Article
Optimized Euler Totient Function for Multiple Evaluations

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • sieve
  • number-theory
  • euler-totient
Practice Tags :
  • Mathematical
  • number-theory
  • sieve

Similar Reads

    Euler Totient for Competitive Programming
    What is Euler Totient function(ETF)?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 \phi(n) .For example the below table shows the ETF value of first 15 positive integers: 3 Important Properties of Euler Totie
    8 min read
    Euler's Totient Function
    Given an integer n, find the value of Euler's Totient Function, denoted as Φ(n). The function Φ(n) represents the count of positive integers less than or equal to n that are relatively prime to n. Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are re
    10 min read
    Count of non co-prime pairs from the range [1, arr[i]] for every array element
    Given an array arr[] consisting of N integers, the task for every ith element of the array is to find the number of non co-prime pairs from the range [1, arr[i]]. Examples: Input: N = 2, arr[] = {3, 4}Output: 2 4Explanation: All non-co-prime pairs from the range [1, 3] are (2, 2) and (3, 3).All non-
    13 min read
    Generate an array having sum of Euler Totient Function of all elements equal to N
    Given a positive integer N, the task is to generate an array such that the sum of the Euler Totient Function of each element is equal to N. Examples: Input: N = 6Output: 1 6 2 3 Input: N = 12Output: 1 12 2 6 3 4 Approach: The given problem can be solved based on the divisor sum property of the Euler
    5 min read
    Count all possible values of K less than Y such that GCD(X, Y) = GCD(X+K, Y)
    Given two integers X and Y, the task is to find the number of integers, K, such that gcd(X, Y) is equal to gcd(X+K, Y), where 0 < K <Y. Examples: Input: X = 3, Y = 15Output: 4Explanation: All possible values of K are {0, 3, 6, 9} for which GCD(X, Y) = GCD(X + K, Y). Input: X = 2, Y = 12Output:
    8 min read
    Count of integers up to N which are non divisors and non coprime with N
    Given an integer N, the task is to find the count of all possible integers less than N satisfying the following properties: The number is not coprime with N i.e their GCD is greater than 1.The number is not a divisor of N. Examples: Input: N = 10 Output: 3 Explanation: All possible integers which ar
    5 min read
    Find the number of primitive roots modulo prime
    Given a prime p . The task is to count all the primitive roots of p .A primitive root is an integer x (1 <= x < p) such that none of the integers x - 1, x2 - 1, ...., xp - 2 - 1 are divisible by p but xp - 1 - 1 is divisible by p . Examples: Input: P = 3 Output: 1 The only primitive root modul
    5 min read
    Compute power of power k times % m
    Given x, k and m. Compute (xxxx...k)%m, x is in power k times. Given x is always prime and m is greater than x. Examples: Input : 2 3 3 Output : 1 Explanation : ((2 ^ 2) ^ 2) % 3 = (4 ^ 2) % 3 = 1 Input : 3 2 3 Output : 0 Explanation : (3^3)%3 = 0 A naive approach is to compute the power of x k time
    15+ min read
    Primitive root of a prime number n modulo n
    Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number. Examples: Input : 7 Output : S
    15 min read
    Euler's Totient function for all numbers smaller than or equal to n
    Euler's Totient function ?(n) for an input n is the 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. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences