Java Program to Find GCD and LCM of Two Numbers

This is java program to find the gcd and lcm of given two numbers. GCD is calculated using Euclidean Algorithm. LCM is found using factorization method.

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

  1. //This is sample program to calculate the GCD and LCM of two given numbers
  2. import java.util.Scanner;
  3.  
  4. public class GCD_LCM 
  5. {
  6.     static int gcd(int x, int y)
  7.     {
  8.         int r=0, a, b;
  9.         a = (x > y) ? x : y; // a is greater number
  10.         b = (x < y) ? x : y; // b is smaller number
  11.  
  12.         r = b;
  13.         while(a % b != 0)
  14.         {
  15.             r = a % b;
  16.             a = b;
  17.             b = r;
  18.         }
  19.         return r;
  20.     }
  21.  
  22.     static int lcm(int x, int y)
  23.     {
  24.         int a;
  25.         a = (x > y) ? x : y; // a is greater number
  26.         while(true)
  27.         {
  28.             if(a % x == 0 && a % y == 0)
  29.                 return a;
  30.             ++a;
  31.         }	
  32.     }
  33.  
  34.     public static void main(String args[])
  35.     {
  36.         Scanner input = new Scanner(System.in);
  37.         System.out.println("Enter the two numbers: ");
  38.         int x = input.nextInt();
  39.         int y = input.nextInt();
  40.  
  41.         System.out.println("The GCD of two numbers is: " + gcd(x, y));
  42.         System.out.println("The LCM of two numbers is: " + lcm(x, y));
  43.         input.close();		
  44.     }
  45. }

Output:

$ javac GCD_LCM.java
$ java GCD_LCM
 
Enter the two numbers: 
15
25
The GCD of two numbers is: 5
The LCM of two numbers is: 75
 
Enter the two numbers: 
5
8
The GCD of two numbers is: 1
The LCM of two numbers is: 40

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.