How can I use python to find all the primitive roots of a number for which it exists?

1.2k Views Asked by At

See definition of primitive roots here.

I have obtained the following code from here:

from math import gcd as bltin_gcd

def primRoots(modulo):
    required_set = {num for num in range(1, modulo) if bltin_gcd(num, modulo) }
    return [g for g in range(1, modulo) if required_set == {pow(g, powers, modulo)
            for powers in range(1, modulo)}]

print(primRoots(17))

I am not a programmer but I have python 3.6 installed on my computer. I used the above code because all I needed was to copy and paste to run it.

The problem for me is that the above doesn't return an answer if I insert a non-prime input for which a primitive root exists (such as 6).

Can any changes to the code be made so that I get an output every time I input a number of the form: $1, 2, 4, p^k, 2p^k$, where $p$ is a prime number and $k$ is an integer $\ge 1$?

1

There are 1 best solutions below

2
On BEST ANSWER

Instead of "if gcd(modulo, num)" you should use "if gcd(modulo, num) == 1". This works for 6 on my machine, correctly predicting that mod 6 the only primitive root is 5. Your code only works on primes because the "if gcd(modulo, num)" check, without an == 1, is entirely useless and so your required set is always range(1, modulo), which happens to be the correct range if and only if your modulus is prime.