/*
 * Euclid.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `JSGL, a Scientific Graphics Library for Java'
 * section: `Example - Subclassing java.util.Random'
 *
 * We implement Euclid's algorithm for finding the greatest common divisor
 * of two integers. We use this to find GCDs and LCMs of numbers entered
 * by the user.
 */
import uk.co.jscieng.*;

class Euclid
{
  // The gcd method implements Euclid's algorithm.
  // If b does not divide exactly into a, then it is
  // mathematically true that GCD(a, b) = GCD(b, a % b).
  // If b does divide exactly, then GCD(a, b) = b. We
  // catch this case in the recursive call to gcd, as
  // opposed to doing so immediately.
  public static int gcd(int a, int b)
  {
    if (b != 0)
    {
      return gcd(b, a % b);
    }
    else
    {
      return a;
    }
  }


  // The main method performs a simple loop.
  public static void main(String[] argv)
  {
    String s;
    int a, b, g;

    // Start the program
    SciGraph.showText();
    SciGraph.println("This program computes GCDs/LCMs");

    do
    {
      SciGraph.println();

      // Get the first argument and convert it into an integer.
      SciGraph.print("Enter the first argument: ");
      s = SciGraph.readln();
      a = Integer.parseInt(s);

      // Get the second argument and convert it into an integer.
      SciGraph.print("Enter the second argument: ");
      s = SciGraph.readln();
      b = Integer.parseInt(s);

      // Compute and display their GCD and LCM.
      SciGraph.println("Their GCD is " + gcd(a,b));
      SciGraph.println("Their LCM is " + a*b/gcd(a,b));

      // Loop around again if the user wants to continue.
      SciGraph.print("Do you want to compute another "
                     +"GCD/LCM (y/n)? ");
      s = SciGraph.readln();
    }
    while (s.equals("y"));
  }
}

