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:
JUnit 5 for Kotlin Developers
Java Program to Implement Gale Shapley Algorithm
Guide to Java 8’s Collectors
Refactoring Design Pattern với tính năng mới trong Java 8
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Giới thiệu Google Guice – Injection, Scope
Base64 encoding và decoding trong Java 8
Spring 5 and Servlet 4 – The PushBuilder
Jackson Ignore Properties on Marshalling
Spring WebClient vs. RestTemplate
Java Program to Implement Flood Fill Algorithm
Introduction to Spring Data MongoDB
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Java Program to Implement Bit Array
How to Get the Last Element of a Stream in Java?
Logout in an OAuth Secured Application
Java Program to Implement the Bin Packing Algorithm
Configuring a DataSource Programmatically in Spring Boot
Overview of Spring Boot Dev Tools
Java Program to Check Cycle in a Graph using Graph traversal
Lớp LinkedHashMap trong Java
Java Program to Implement Euclid GCD Algorithm
Using JWT with Spring Security OAuth
Server-Sent Events in Spring
Java Program to Check whether Directed Graph is Connected using DFS
Java Program to Implement Graph Structured Stack
Java Program to Implement Quick Sort with Given Complexity Constraint
Java Program to Perform LU Decomposition of any Matrix
Serverless Functions with Spring Cloud Function
Generating Random Dates in Java
LinkedList trong java