In: Computer Science
Using the code below as a template, write a program that asks the user to enter two integers, and finds and prints their greatest common denominator (GCD) in Java!
package cp213; import java.util.Scanner; public class Lab01 { /** * @param a * @param b * @return */ public static int gcd(int a, int b) { // your code here } /** * @param args */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int a = 0; int b = 0; int c = 0; // Read an integer from the keyboard. System.out.print("Enter a (0 to quit): "); a = keyboard.nextInt(); // your code here // gcd function call c = Lab01.gcd( a, b ); // your code here } }
package cp213; import java.util.Scanner; public class Lab01 { /** * @param a * @param b * @return */ public static int gcd(int a, int b) { if (a == 0 || b == 0) return 0; else if (a == b) return a; else if (a > b) return gcd(a - b, b); else return gcd(a, b - a); } /** * @param args */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int a = 0; int b = 0; int c = 0; while (true) { // Read an integer from the keyboard. System.out.print("Enter a number(0 to quit): "); a = keyboard.nextInt(); if (a == 0) break; System.out.print("Enter another number: "); b = keyboard.nextInt(); // gcd function call c = Lab01.gcd(a, b); System.out.println("GCD of " + a + " and " + b + " is " + c + "\n"); } } }