import java.util.Scanner; /* GCD_Tester.java ** Java application for testing a recursive method that computes the ** GCD (greatest common divisor) of two integers recursively. ** ** Authors: R. McCloskey and < lab team members > ** Known defects: ... */ public class GCD_Tester { private static Scanner keyboard; private static int depth; /* Returns the greatest common divisor of the two int values given. ** Uses recursion and narrates its execution! ** pre: k >= 0 && m >= 0 && k+m > 0 */ public static int gcdViaRec(int k, int m) { depth++; printMessage(String.format("Received k:%d and m:%d\n", k, m)); int result; // MISSING CODE GOES HERE printMessage(String.format("Returning %d having received k:%d and m:%d\n", result, k, m)); depth--; return result; } /* Returns the greatest common divisor of the two int values given. ** Uses a loop. ** pre: k >= 0 && m >= 0 && k+m > 0 */ public static int gcdViaLoop(int k, int m) { // ensure that k >= m by swapping their values if k < m if (k < m) { int temp = k; k = m; m = temp; } while (m != 0) { int newM = k % m; // replace k by m and m by k % m k = m; m = newM; } return k; } // main () method for testing // -------------------------- public static void main(String[] args) { final String kPrompt = "Enter a value for k: "; final String mPrompt = "Enter a value for m: "; keyboard = new Scanner(System.in); int k, m = 0; do { k = getInt(kPrompt); if (k >= 0) { depth = -1; m = getInt(mPrompt); int result = gcdViaRec(k, m); int correctResult = gcdViaLoop(k,m); System.out.println("\nYour method produced " + result); System.out.println("The correct result is " + correctResult); System.out.println(); } } while (k >= 0); System.out.println("Goodbye."); } /* Prints the specified string, indented according to the value of 'depth'. */ private static void printMessage(String s) { printSpaces(3*depth); System.out.print(s); } /* Prints the specified # of spaces. */ private static void printSpaces(int r) { for (int i = 0; i !=r; i++) { System.out.print(' '); } } /* Displays the given prompt and returns the String entered at the keyboard ** in response. */ private static int getInt(String prompt) { int result = -1; boolean tryAgain = true; while (tryAgain) { System.out.print(prompt); try { String response = keyboard.nextLine().trim(); result = Integer.parseInt(response); tryAgain = false; } catch (NumberFormatException e) { System.out.println("** Invalid response; try again\n"); } } return result; } }