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.
Hi, I had a python solution to the problem based on baby-step giant-step algorithm to find discrete log but I got TLE, if someone can help me to optimize the solution, thanks in advance.
"""
Here I show how to find a discrete log using baby step big step algorithms,
Code
"""
def gcd(a,b):
if a%b==0:return b,0,1
r,x,y=gcd(b,a%b)
return r,y,x-(a/b)*y
def inv(a,b,m):
k=(a**2-5*b**2)%m
g,k,_=gcd(k,m)
k%=m
if g!=1:return None
return ((a*k)%m,(-b*k)%m)
def pow(x,n,one,mul):
r=one
while n:
if n%2:r=mul(r,x)
n/=2
x=mul(x,x)
return r
xinv=inv(x)
if not xinv:return -1
r=y
d={}
for i in range(1,step+1):
r=mul(r,xinv)
if r not in d:d[r]=i
current=one
ret=step**2+1
r=pow(x,step,one,mul)
for i in range(0,step+1):
if current in d:
ret=min(i*step+d[current],ret)
current=mul(current,r)
return -1 if ret==step+1 else ret
Period
You are viewing a single comment's thread. Return to all comments →
Hi, I had a python solution to the problem based on baby-step giant-step algorithm to find discrete log but I got TLE, if someone can help me to optimize the solution, thanks in advance.
""" Here I show how to find a discrete log using baby step big step algorithms, Code """
def gcd(a,b): if a%b==0:return b,0,1 r,x,y=gcd(b,a%b) return r,y,x-(a/b)*y
def inv(a,b,m): k=(a**2-5*b**2)%m g,k,_=gcd(k,m) k%=m if g!=1:return None return ((a*k)%m,(-b*k)%m)
def pow(x,n,one,mul):
import math
def dLog(x,y,one,mul,inv,group_size): step=int(math.sqrt(group_size))+1
def solve(a,b,m):
T=input()
for i in range(T): a,b,m=map(int,raw_input().strip().split()) print solve(a,b,m)