Write Java program to Find the (GCD) Greatest Common Divisor


This Java program prompts the user to enter two numbers, and then calculates and outputs their greatest common divisor (GCD). The GCD is found using the Euclidean algorithm, which repeatedly divides the larger number by the smaller number, taking the remainder at each step, until the remainder is zero. The final nonzero remainder is the GCD.

Here's a step-by-step breakdown of what the program does:

  • Create a Scanner object to read user input.
  • Initialize variables num1, num2, rem, X, and Y to zero.
  • Prompt the user to enter num1 and num2.
  • Compare num1 and num2, and assign the larger number to X and the smaller number to Y.
  • Calculate the remainder of X divided by Y, and assign it to rem.
  • While rem is not equal to zero, do the following: a. Assign the value of Y to X. b. Assign the value of rem to Y. c. Calculate the new remainder of X divided by Y, and assign it to rem.
  • Output the value of Y as the GCD.

Source Code

import java.util.Scanner;
public class Find_GCD
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int num1 = 0, num2 = 0;
		int rem = 0, X = 0, Y = 0;
 
		System.out.printf("Enter the Number 1 : ");
		num1 = input.nextInt();
		System.out.printf("Enter the Number 2 : ");
		num2 = input.nextInt();
 
		if (num1 > num2)
		{
			X = num1;
			Y = num2;
		}
		else 
		{
			X = num2;
			Y = num1;
		}
		rem = X % Y;
		while(rem != 0) 
		{
			X = Y;
			Y = rem;
			rem = X % Y;
		}
		System.out.println("Greatest Common Divisor is : "+ Y);
	}
}

Output

Enter the Number 1 : 23
Enter the Number 2 : 3
Greatest Common Divisor is : 1

Example Programs