We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Primitive root for a prime P is number g in [1,P-1] such that g^x mod P gives all [1,P-1], with x in [1,P-2]
Need to find:
1. Smallest primitive root of p
2. Total primitive roots of p
Solution logic:
1. determine all the prime factor of phi = p - 1 as p1, p2, ... pk
2. For each candidate g
for each prime factor pj
if g^(phi/pj) mod != 1
if above condition is met for all pj, it is a root
3. Once one primitive root is found, others can be obtained as g^m where gcd(m, phi) == 1 i.e. they should be coprime
defget_prime_factors(n:int)->set[int]:"""Fast prime factorization using trial division up to sqrt(n)."""factors=set()whilen%2==0:factors.add(2)n//= 2f=3whilef*f<=n:whilen%f==0:factors.add(f)n//= ff+=2ifn>1:factors.add(n)returnfactors
defprimitive_root_check(g:int,phi_factors:list[int],p:int)->bool:"""Check if g is a primitive root modulo p."""returnall(pow(g,(p-1)// q, p) != 1 for q in phi_factors)
defprimitive_roots(p:int)->set[int]:"""Find all primitive roots modulo p."""phi_factors=list(get_prime_factors(p-1))# Find smallest primitive rootforginrange(2,p):ifprimitive_root_check(g,phi_factors,p):primitive=gbreak# Generate all primitive roots from the smallest oneroots={pow(primitive,k,p)forkinrange(1,p)ifgcd_AB(k,p-1)==1}returnroots
Primitive Problem
You are viewing a single comment's thread. Return to all comments →
Primitive root for a prime P is number g in [1,P-1] such that g^x mod P gives all [1,P-1], with x in [1,P-2]
Need to find: 1. Smallest primitive root of p 2. Total primitive roots of p
Solution logic: 1. determine all the prime factor of phi = p - 1 as p1, p2, ... pk 2. For each candidate g for each prime factor pj if g^(phi/pj) mod != 1
'''