SporkApp Source Code

( <-- Back to SporkApp )

Title:"Greatest Common Divisor Calculator"
Author:Sporkman
Last updated:
10/01/11  12:22 pm

Source code:


string xs, ys;

while (true)
{
   print("Welcome to the Greatest Common Divisor (GCD) Calculator.\n\n");
   print("Enter the two numbers to determine the GCD of below...\n\n\n");

   print("Numbers:  ");

   input a = print_input_field(6,12,xs);

   print("  ");

   input b = print_input_field(6,12,ys);

   print("\n\n   ");

   print_input_button("Calculate GCD");

   print("\n\n\n");

   if ( xs!="" || ys!="" )
   {
      int x = intval(xs);
      int y = intval(ys);

      if ( x<1 || y<1 )
      {
         print("** Error: Both numbers must be positive.\n\n\n\n\n");
      }
      else
      {
         int g = gcd(x,y);

         print("   GCD = " + str(g) + "\n\n");

         int xl = length(str(x));
         int yl = length(str(y));
         int l = max(xl,yl);

         print("   " + strf_int(x,l,"") + " = " + str(g) + " * " + str(x/g) + "\n");
         print("   " + strf_int(y,l,"") + " = " + str(g) + " * " + str(y/g) + "\n\n");
      }
   }
   else
   {
      print("\n\n\n\n\n");
   }

   load_user_input();

   xs = get_input_value(a);
   ys = get_input_value(b);
}

function int gcd ( int x, int y )
{
   int a, b, q, r;

   if ( x>y )
   {
      a = x;
      b = y;
   }
   else
   {
      a = y;
      b = x;
   }

   while ( b>0 )
   {
      q = a/b;
      r = a - q*b;

      a = b;
      b = r;
   }

   return a;
}

function int max ( int a, int b )
{
   if ( a>b )
   {
      return a;
   }
   return b;
}







sporkforge