// L-23 MCS 360 Fri 15 Oct 2010 : gcd_stack.cpp

/* We use the stack of function calls to turn the recursive
   function to compute the greatest common divisor into
   an iterative function. */

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

int gcd ( int a, int b );
// returns the greatest common divisor of a and b

int gcd_stack ( int a, int b );
// builds the stack of recursive function calls
// in an iterative version of the gcd implementation

void write ( stack< vector<int> > &s );
// writes the stack s of arguments 

int main()
{
   cout << "give x : ";
   int x; cin >> x;

   cout << "give y : ";
   int y; cin >> y;

   int d = gcd_stack(x,y);
   cout << "gcd(" << x << "," << y << ") = "
        << d << endl;
   cout << "gcd(" << x << "," << y << ") = "
        << gcd(x,y) << endl;

   return 0;
}

int gcd ( int a, int b )
{
   int r = a % b;
   if(r == 0)
      return b;
   else
      return gcd(b,r);
}

int gcd_stack ( int a, int b )
{
   int result;

   stack< vector<int> > s;

   vector<int> v;
   v.push_back(a);
   v.push_back(b);
   s.push(v);

   while(!s.empty())
   {
      cout << "the stack : ";
      write(s);
      vector<int> e = s.top();
      s.pop();

      int r = e[0] % e[1];
      if(r == 0)
         result = e[1];
      else
      {
         e[0] = e[1]; e[1] = r;
         s.push(e);
      }
   }
   return result;
}

void write ( stack< vector<int> > &s )
{
   for(stack< vector<int> > t = s; !t.empty(); t.pop())
   {
      vector<int> v = t.top();
      cout << "(" << v[0] << "," << v[1] << ")";
   }
   cout << endl;
}

