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 Check for balanced parenthesis by using Stacks
Java Program to Perform Searching Based on Locality of Reference
Java Program to Find a Good Feedback Edge Set in a Graph
CyclicBarrier in Java
Using a Mutex Object in Java
HttpClient Basic Authentication
Spring Boot - Service Components
Using the Map.Entry Java Class
The DAO with Spring and Hibernate
Spring Boot - Introduction
Java Program to Perform LU Decomposition of any Matrix
Java Program to Implement Best-First Search
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Giới thiệu về Stream API trong Java 8
Quick Guide to Spring Controllers
Creating a Custom Starter with Spring Boot
Java Program to Perform Cryptography Using Transposition Technique
Query Entities by Dates and Times with Spring Data JPA
Convert char to String in Java
Migrating from JUnit 4 to JUnit 5
Java Program to Solve the Fractional Knapsack Problem
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
DistinctBy in the Java Stream API
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Implement Attribute API
Java Program to Implement LinkedHashMap API
Java Program to Represent Graph Using Adjacency List
Java Program to Check Multiplicability of Two Matrices
Using JWT with Spring Security OAuth
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Using a Spring Cloud App Starter
Java Program to Implement Ford–Fulkerson Algorithm