Q:

Java program to find the (GCD) Greatest Common Divisor

belongs to collection: Java Basic Programs

0

Java program to find the (GCD) Greatest Common Divisor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to find the (LCM) Lowest Common Multi... >>
<< Java program to find the roots of a quadratic equa...