# Arup Guha
# 10/26/2026
# Discrete Log Algorithm that runs in O(sqrt(p)) time

# Finds x such that a to the x = b mod p. Assumes that a is a generator
# mod p which guarantees an answer exists. 1 <= b < p.
def discretelog(a,b,p):

    # I'll need this later.
    bModInv = modInv(b,p)

    x = int(p**.5) + 1

    # Make a chart a^0, a^1, a^2, ..., a^x, where we map answer to exponent.
    powMap = {}
    val = 1
    for i in range(x):
        powMap[val] = i
        val = (val*a)%p

    # This is what we'll use to exponentiate a^x, a^(2x) etc.
    step = pow(a,x,p)
    curExp = 0

    # Now we'll start our search.
    curVal = 1
    for i in range(x):

        # Current running value of 2^x or 2^(2x) etc.
        curVal = (curVal*step)%p
        curExp += x

        # Value I am looking for in the map.
        magicNum = (curVal*bModInv)%p

        # We found it!
        if magicNum in powMap:
            return curExp - powMap[magicNum]

    return -1


# Returns a list storing [x, y, gcd(a,b)] where ax + by = gcd(a,b).
def EEA(a,b):

    # End of algorithm, 1*a + 0*b = a
    if b == 0:
        return [1,0,a]

    # Recursive case.
    else:

        # Next quotient and remainder.
        q = a//b
        r = a%b

        # Algorithm runs on b, r.
        rec = EEA(b,r)

        # Here is how we put the solution back together!
        return [rec[1], rec[0]-q*rec[1], rec[2]]

# Returns the modular inverse of x mod n. Returns 0 if there is no modular
# inverse.
def modInv(x,n):

    # Call the Extended Euclidean.
    arr = EEA(n, x)

    # Indicates that there is no solution.
    if arr[2] != 1:
        return 0

    # Do the wrap around, if necessary.
    if arr[1] < 0:
        arr[1] += n

        # This is the modular inverse.
    return arr[1]

# My small test.
for ans in range(1,100):
    myanswer = discretelog(2,ans,101)
    print(myanswer, pow(2,myanswer,101))
