/** * An implementation of Euclid's GCD algorithm. * @author Karel P. Bergmann */ public class GCD1 { /** * A driver for the GCD method. Requires two integers as parameters. * Output's the GCD of the two integers to the screen. * * @param args Integers a, b * @throws ArrayIndexOutOfBoundsException If fewer than two parameters are provided. * @throws NumberFormatException If either of the first two parameters is not an integer. */ public static void main (String [] args) { int a = 0; int b = 0; /* Try to acquire a */ try { a = Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("Must supply two command line arguments."); System.exit (1); } catch (NumberFormatException e) { System.out.println ("First argument is not an integer."); System.exit (1); } /* Try to acquire b */ try { b = Integer.parseInt(args[1]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("Must supply two command line arguments."); System.exit (1); } catch (NumberFormatException e) { System.out.println ("Second argument is not an integer."); System.exit (1); } /* Find the GCD of a and b */ System.out.println (gcd (a, b)); } /** * Calculates the greatest common divisor of a and b using the Euclidean algorithm. * GCD (0, a) or GCD (a, 0) = a, if either a < 0 or b < 0, then GCD (a, b) = GCD (|a|, |b|). * * @param a An integer. * @param b Another integer. */ public static int gcd (int a, int b) { /* Test if either argument is 0 */ if (a == 0) return (a); else if (b == 0) return (a); else { /* Take absolute values of a and b */ int p = Math.abs (a); int q = Math.abs (b); //assert (gcd (a, b) == gcd (p, q)); /* Euclidean algorithm */ while (q != 0) { int r = p % q; p = q; q = r; } /* Return GCD */ return (p); } } }