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:
Giới thiệu HATEOAS
Spring Boot - Creating Docker Image
A Guide to JUnit 5
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Program to Implement the RSA Algorithm
Kết hợp Java Reflection và Java Annotations
Java – InputStream to Reader
Spring Boot - Tomcat Deployment
Spring Boot - Tracing Micro Service Logs
Handling Errors in Spring WebFlux
Java Program to Implement Hash Tables Chaining with Binary Trees
Spring Boot - Introduction
Registration with Spring Security – Password Encoding
Java Program to Implement Euler Circuit Problem
Java Program to Implement Find all Forward Edges in a Graph
Java – Write an InputStream to a File
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Perform Partial Key Search in a K-D Tree
Jackson vs Gson
Java Program to Implement Quick sort
Java String to InputStream
Java Program to Implement Skip List
Java Program to Construct an Expression Tree for an Postfix Expression
Easy Ways to Write a Java InputStream to an OutputStream
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Check for balanced parenthesis by using Stacks
Java Program to Implement LinkedHashSet API
Java Program to Implement Sorted Circular Doubly Linked List
Converting Between an Array and a Set in Java
Immutable Objects in Java
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Java Program to Find All Pairs Shortest Path