GTU OOP Program - 9
9). Write a method with following method header. public static int gcd(int num1, int num2) Write a program that prompts the user to enter two integers and compute the gcd of two integers.
import java.util.Scanner; class Program_09 { public static int gcd(int num1, int num2) { int gcd = 1; for (int i = 1; i <= num1 && i <= num2; ++i) { // check if i prefectly divides both num1 and num2 if (num1 % i == 0 && num2 % i == 0) gcd = i; } return gcd; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter First Number : "); int num1 = input.nextInt(); System.out.print("Enter Second Number : "); int num2 = input.nextInt(); int GCD = gcd(num1, num2); System.out.println("GCD of " + num1 + " & " + num2 + " is " + GCD); } }
Output
Comments