![]() |
VOOZH | about |
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 : Smallest primitive root = 3 Explanation: n = 7 3^0(mod 7) = 1 3^1(mod 7) = 3 3^2(mod 7) = 2 3^3(mod 7) = 6 3^4(mod 7) = 4 3^5(mod 7) = 5 Input : 761 Output : Smallest primitive root = 6
A simple solution is to try all numbers from 2 to n-1. For every number r, compute values of r^x(mod n) where x is in the range[0, n-2]. If all these values are different, then return r, else continue for the next value of r. If all values of r are tried, return -1.
An efficient solution is based on the below facts.
If the multiplicative order of a number r modulo n is equal to Euler Totient Function ?(n) ( note that the Euler Totient Function for a prime n is n-1), then it is a primitive root.
1- Euler Totient Function phi = n-1 [Assuming n is prime] 1- Find all prime factors of phi. 2- Calculate all powers to be calculated further using (phi/prime-factors) one by one. 3- Check for all numbered for all powers from i=2 to n-1 i.e. (i^ powers) modulo n. 4- If it is 1 then 'i' is not a primitive root of n. 5- If it is never 1 then return i;.
Although there can be multiple primitive roots for a prime number, we are only concerned with the smallest one. If you want to find all the roots, then continue the process till p-1 instead of breaking up by finding the first primitive root.
Output:
Smallest primitive root of 761 is 6
Time Complexity : O(n^2 * logn)
Space Complexity : O(sqrt(n))