public class GCDCalc
1: //GCDCalc.java
3: import java.util.Scanner;
5: public class GCDCalc
6: {
7: /* Determine the greatest common divisor
8: of two numbers, e.g. GCD(8, 12) = 4
9: */
10: public static int gcdCalculator(int inNum1, int inNum2)
11: {
12: int gcdVal; // Holds GCD results
14: if (inNum1 == inNum2) // Base case: Numbers are equal
15: {
16: gcdVal = inNum1; // Return value
17: }
18: else // Recursive case: subtract smaller from larger
19: {
20: if (inNum1 > inNum2) // Call function with new values
21: {
22: gcdVal = gcdCalculator(inNum1 - inNum2, inNum2);
23: }
24: else // n1 is smaller
25: {
26: gcdVal = gcdCalculator(inNum1, inNum2 - inNum1);
27: }
28: }
30: return gcdVal;
31: }
33: public static void main (String[] args)
34: {
35: Scanner scnr = new Scanner(System.in);
36: int gcdInput1; // First input to GCD calc
37: int gcdInput2; // Second input to GCD calc
38: int gcdOutput; // Result of GCD
40: // Print program function
41: System.out.println
42: (
43: "This program outputs the greatest \n"
44: + "common divisor of two numbers."
45: );
47: // Prompt user for input
48: System.out.print("Enter first number: ");
49: gcdInput1 = scnr.nextInt();
51: System.out.print("Enter second number: ");
52: gcdInput2 = scnr.nextInt();
54: // Check user values are > 1, call recursive GCD function
55: if ((gcdInput1 < 1) || (gcdInput2 < 1))
56: {
57: System.out.println("Note: Neither value can be below 1.");
58: }
59: else
60: {
61: gcdOutput = gcdCalculator(gcdInput1, gcdInput2);
62: System.out.println
63: (
64: "Greatest common divisor = "
65: + gcdOutput
66: );
67: }
68: }
69: }