Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Find GCD of two Numbers


In this article, we will understand how to find the GCD of two numbers in Java. Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them.

Below is a demonstration of the same −

Input

Suppose our input is −

Value_1 : 18
Value_2 : 24

Output

The desired output would be −

GCD of the two numbers : 6

Algorithm

Step1- Start
Step 2- Declare three integers: input_1, inpur_2 and gcd
Step 3- Prompt the user to enter two integer value/ Hardcode the integer
Step 4- Read the values
Step 5- Check that the number divides both (x and y) numbers completely or not. If
divides completely store it in a variable.
Step 6- Display the ‘i’ value as GCD of the two numbers
Step 7- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool Java Program to Find GCD of two Numbers.

import java.util.Scanner;
public class GCD{
   public static void main(String[] args){
      int input_1 , input_2 , gcd ;
      Scanner reader = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter a first number: ");
      input_1 = reader.nextInt();
      System.out.print("Enter a second number: ");
      input_2 = reader.nextInt();
      gcd = 1;
      for(int i = 1; i <= input_1 && i <= input_2; i++){
         if(input_1%i==0 && input_2%i==0)
         gcd = i;
      }
      System.out.printf("\nThe GCD of %d and %d is: %d", input_1, input_2, gcd);
   }
}

Output

A reader object has been defined
Enter a first number: 24
Enter a second number: 18
The GCD of 24 and 18 is: 6

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class GCD{
   public static void main(String[] args){
      int input_1 , input_2 , gcd ;
      input_1 = 12;
      input_2 = 18;
      gcd = 1;
      System.out.print("The first number is " + input_1);
      System.out.print("\nThe second number is " + input_2);
      for(int i = 1; i <= input_1 && i <= input_2; i++){
         if(input_1%i==0 && input_2%i==0)
         gcd = i;
      }
      System.out.printf("\nThe GCD of %d and %d is: %d", input_1, input_2, gcd);
   }
}

Output

The first number is 24
The second number is 18
The GCD of 24 and 18 is: 6