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
advertisement

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.