# L-17 MCS 275 Fri 17 Feb 2017 : gcdstack.py
"""
We construct the stack of function calls
of a recursive gcd function.
"""

def gcd(alpha, beta):
    """
    Returns greatest common divisor
    of the numbers alpha and beta.
    """
    rest = alpha % beta
    if rest == 0:
        return beta
    else:
        return gcd(beta, rest)

def gcdstack(alpha, beta):
    """
    Builds the stack of function calls in
    a recursive gcd for alpha and beta.
    """
    from ast import literal_eval
    stk = ['gcd(%d,%d)' % (alpha, beta)]
    while stk != []:
        print('S =', stk)
        exp = stk.pop(0)
        (alpha, beta) = literal_eval(exp[3:len(exp)])
        rest = alpha % beta
        if rest == 0:
            result = beta
        else:
            stk.insert(0, 'gcd(%d,%d)' % (beta, rest))
    return result

def main():
    """
    Prompts the user for two numbers
    and uses a stack to evaluate the gcd.
    """
    alpha = int(input('give a : '))
    beta = int(input('give b : '))
    result = gcdstack(alpha, beta)
    print('gcd(%d, %d) = %d' % (alpha, beta, result))

if __name__ == "__main__":
    main()
