// HW08_2c.java // Tim Hilby // Created on April 12, 2006 import java.util.Scanner; public class HW08_2c { // calculates the gcd public static int gcd(int num1, int num2) { // return num2 if num2 <= num1 and num2 divides num1 if ((num2 <= num1) && (num1 % num2 == 0)) { return num2; } // return gcd(num2, num1) if num1 < num2 else if (num1 < num2) { return gcd(num2, num1); } // return gcd(num2, num1 % num2) otherwise else { return gcd(num2, num1 % num2); } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("This program calculates the "); System.out.println("greatest common divisor"); System.out.println("of two positive numbers."); int a = 0; int b = 0; System.out.println("Enter the two numbers: (0 to quit)"); a = scan.nextInt(); // don't bother reading the second number if the first is 0 if (a != 0) { b = scan.nextInt(); } while ((a != 0) && (b != 0)) { if ((a < 0) || (b < 0)) { System.out.println("Both numbers must be positive!"); } else { System.out.println("Answer: " + gcd(a, b)); } System.out.println("Enter the two numbers: (0 to quit)"); a = scan.nextInt(); // don't bother reading the second number if the first is 0 if (a != 0) { b = scan.nextInt(); } } } }