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 implement Bit Set
Java IO vs NIO
Hướng dẫn sử dụng Java Annotation
Consuming RESTful Web Services
Hướng dẫn Java Design Pattern – DAO
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
How to Kill a Java Thread
Spring Boot - Eureka Server
Setting the Java Version in Maven
Working With Maps Using Streams
MyBatis with Spring
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Java Program to Implement an Algorithm to Find the Global min Cut in a Graph
Convert Hex to ASCII in Java
Quick Intro to Spring Cloud Configuration
Java Program to Solve a Matching Problem for a Given Specific Case
Lớp HashMap trong Java
A Guide to Spring Boot Admin
Java Program to Implement Adjacency Matrix
Using Spring @ResponseStatus to Set HTTP Status Code
Java Program to Implement Fibonacci Heap
Guide to Character Encoding
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Fixing 401s with CORS Preflights and Spring Security
Cachable Static Assets with Spring MVC
Static Content in Spring WebFlux
Java Stream Filter with Lambda Expression
Java Program to Find the Minimum value of Binary Search Tree
Java Program to Implement Word Wrap Problem
Introduction to Spring Cloud Rest Client with Netflix Ribbon
Spring Boot - Web Socket
Guide to System.gc()