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.
//This is sample program to calculate the GCD and LCM of two given numbers import java.util.Scanner; public class GCD_LCM { static int gcd(int x, int y) { int r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } static int lcm(int x, int y) { int a; a = (x > y) ? x : y; // a is greater number while(true) { if(a % x == 0 && a % y == 0) return a; ++a; } } public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Enter the two numbers: "); int x = input.nextInt(); int y = input.nextInt(); System.out.println("The GCD of two numbers is: " + gcd(x, y)); System.out.println("The LCM of two numbers is: " + lcm(x, y)); input.close(); } }
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
Related posts:
Java Program to Perform String Matching Using String Library
Java Program to Find kth Largest Element in a Sequence
Java Program to Implement AVL Tree
Convert String to int or Integer in Java
Lớp Collectors trong Java 8
Overflow and Underflow in Java
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
Java Program to Implement Miller Rabin Primality Test Algorithm
A Guide to BitSet in Java
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Guide to Dynamic Tests in Junit 5
Java Program to Implement Dijkstra’s Algorithm using Set
Java Program to Implement SimpeBindings API
Java Program to Implement HashTable API
An Introduction to ThreadLocal in Java
Java Program to Implement LinkedHashSet API
Java Program to Find Path Between Two Nodes in a Graph
Java Program for Topological Sorting in Graphs
Java Program to Find a Good Feedback Vertex Set
Guide to Guava Multimap
How to Store Duplicate Keys in a Map in Java?
A Quick JUnit vs TestNG Comparison
Comparing Two HashMaps in Java
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Transactions with Spring and JPA
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Perform Quick Sort on Large Number of Elements
Create a Custom Auto-Configuration with Spring Boot
Java Program to Implement Leftist Heap
Quick Guide to Spring Bean Scopes
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java