I understand that my code's complexity isn't the best, and I thought it might take 3 - 6 minutes running, but I gave it 15 minutes and it didn't stop. How do I know if it got stuck somewhere or it's just still running? and How can I improve it?
import random import time def is_prime(m): """ probabilistic test for compositeness of m>30 adds a trivial sieve to quickly eliminate divisibility by small primes. """ if m in [2,3,5,7,11,13,17,19,23,29]: return True # treats small primes separately for prime in [2,3,5,7,11,13,17,19,23,29]: if m % prime == 0: return False for i in range(0,100): a = random.randint(1,m-1) # a is a random integer in [1..m-1] if pow(a,m-1,m) != 1: return False return True def order_safe_prime(g,p): """ computes the order of g modulo a safe prime, p """ if g<1 or g>p-1: return str.format("g={} is out of range", g) elif not is_prime(p): return str.format("{} is not a prime", p) q=(p-1)//2 if not is_prime(q): return str.format("q={} is not a prime", (p-1)//2) else: if g==1: return 1 if g==p-1: return 2 if pow(g,q,p)==1: return q if pow(g,p-1,p)==1: return p-1 def stats_ord_secure(p,times=10000): cnt1=0 cnt2=0 for i in range(times): g=random.randint(2,p-2) if order_safe_prime(g,p)==(p-1)/2: cnt1+=1 if order_safe_prime(g,p)==(p-1): cnt2+=1 return ((cnt1/times,cnt2/times)) For example running :
>>>stats_ord_secure((2**1001)+188151) would take more than 15 minutes !
is_primeis_primeis very expensive (because prime number tests always are).