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:
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); } }
Enter the Number 1 : 23 Enter the Number 2 : 3 Greatest Common Divisor is : 1
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions