// GCD.java // calculate GCD of a and b // Usage: java GCD a b (a >= b) public class GCD { public static void main (String[] args) { // check number of arguments if (args.length != 2) { System.err.println("Usage: java GCD "); return; // usually, we use System.exit(1); } // initialize a, b int a = 0, b = 0; a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); // compute and report the GCD System.out.println("The GCD of " + a + " and " + b + " is " + gcd(a, b)); } // method to compute the GCD of a and b public static int gcd(int a, int b) { // if b > a, then swap the two if (b > a) { int temp = b; b = a; a = temp; } // compute initial value of remainder int r = a % b; // iteratively update a, b, r while (r != 0) { a = b; b = r; r = a % b; } // return b, the GCD return b; } }