# L-14 MCS 275 Fri 15 Feb 2008 : gcdstack.py

# We construct the stack of function calls
# of a recursive gcd function.

def gcd(a,b):
   """
   Returns greatest common divisor
   of the numbers a and b.
   """
   r = a % b 
   if r == 0: 
      return b 
   else: 
      return gcd(b,r) 
  
def gcdstack(a,b):
   """
   Builds the stack of function calls
   in a recursive gcd for a and b.
   """
   S = []
   S.insert(0,'gcd(%d,%d)' % (a,b))
   while S != []:
      print 'S =', S
      e = S.pop(0)
      (a,b) = eval(e[3:len(e)])
      r = a % b
      if r == 0:
         result = b
      else:
         S.insert(0,'gcd(%d,%d)' % (b,r))
   return result

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

main()
