Java program to find the (GCD) Greatest Common Divisor

Given two numbers, we have to find the (GCD) Greatest Common Divisor.
Submitted by Nidhi, on February 26, 2022

Problem Solution:

In this program, we will read two integer numbers from user and find the Greatest Common Divisor.

Program/Source Code:

The source code to find the GCD is given below. The given program is compiled and executed successfully.

// Java program to find the 
// Greatest Common Divisor

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int num1 = 0;
    int num2 = 0;
    int rem = 0;
    int X = 0;
    int Y = 0;

    Scanner SC = new Scanner(System.in);

    System.out.printf("Enter Number1: ");
    num1 = SC.nextInt();

    System.out.printf("Enter Number2: ");
    num2 = SC.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.printf("Greatest Common Divisor is: %d\n", Y);
  }
}

Output:

Enter Number1: 16
Enter Number2: 28
Greatest Common Divisor is: 4

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we read two integer numbers from the user using the Scanner class. Then we calculated the Greatest Common Divisor (GCD) and printed the result.

Java Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.