GCD Program in Java

This is a Java Program to Compute GCD. Greatest Common Divisor of a given set of numbers is the highest number which divides exactly every number of the given set.

Enter the two numbers as input. Now we use loops to find GCD of two given numbers.

Here is the source code of the Java Program to Compute GCD. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import static java.lang.StrictMath.min;
  2. import java.util.Scanner;
  3. public class GCD
  4. {
  5.     public static void main(String args[])
  6.     {
  7.         int a, b, hcf = 1;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter First Number:");
  10.         a = s.nextInt();
  11.         System.out.print("Enter Second Number:");
  12.         b = s.nextInt();
  13.         int n = min(a,b);
  14.         for(int i = 2; i < n; i++)
  15.         {
  16.             while(a % i == 0 && b % i==0)
  17.             {
  18.                 hcf = hcf * i;
  19.                 a = a / i;
  20.                 b = b / i;
  21.             }
  22.         }
  23.         System.out.println("Greatest Common Divisor:"+hcf);
  24.     }
  25. }

Output:

$ javac GCD.java
$ java GCD
 
Enter First Number:24
Enter Second Number:16
Greatest Common Divisor:8

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations