Google News
logo
Java Program to Find GCD of Two Numbers
The following example of Java program to find the GCD (Greatest Common Divisor) of two numbers using the Euclidean algorithm :
Program :
import java.util.Scanner;

public class Gcd {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        int num1 = input.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = input.nextInt();

        int gcd = findGcd(num1, num2);

        System.out.println("The GCD of " + num1 + " and " + num2 + " is " + gcd);
    }

    public static int findGcd(int num1, int num2) {
        while (num2 != 0) {
            int temp = num2;
            num2 = num1 % num2;
            num1 = temp;
        }
        return num1;
    }
}
Output :
Enter the first number: 19
Enter the second number: 27
The GCD of 19 and 27 is 1
In this program, the user is prompted to enter two numbers, which are then passed as arguments to the findGcd method. This method uses the Euclidean algorithm to calculate the GCD of the two numbers.

The algorithm involves repeatedly dividing the larger number by the smaller number and assigning the remainder to the larger number. This process is repeated until the smaller number becomes zero, at which point the GCD is the current value of the larger number.

The findGcd method returns the GCD, which is then displayed to the user.