VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-number-of-primitive-roots-modulo-prime/

⇱ Find the number of primitive roots modulo prime - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the number of primitive roots modulo prime

Last Updated : 11 Jul, 2025

Given a prime . The task is to count all the primitive roots of .
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 but xp - 1 - 1 is divisible by . 
Examples: 
 

Input: P = 3 
Output:
The only primitive root modulo 3 is 2. 
Input: P = 5 
Output:
Primitive roots modulo 5 are 2 and 3. 
 


 


Approach: There is always at least one primitive root for all primes. So, using Eulers totient function we can say that f(p-1) is the required answer where f(n) is euler totient function.
Below is the implementation of the above approach: 
 


Output: 
2

 

Time Complexity: O(p * log(min(a, b))), where a and b are two parameters of gcd.

Auxiliary Space: O(log(min(a, b)))

Comment