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:
Command-Line Arguments in Java
Java Program to Implement Double Ended Queue
The StackOverflowError in Java
Spring Boot - Cloud Configuration Client
Spring Boot - Admin Client
Netflix Archaius with Various Database Configurations
Java Program to Implement the Checksum Method for Small String Messages and Detect
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Programmatic Transaction Management in Spring
Java Program to Implement vector
Integer Constant Pool trong Java
Java Copy Constructor
Introduction to the Functional Web Framework in Spring 5
JWT – Token-based Authentication trong Jersey 2.x
Java – Get Random Item/Element From a List
Java Program to Implement VList
Spring MVC + Thymeleaf 3.0: New Features
Receive email by java client
Java 9 Stream API Improvements
Constructor Dependency Injection in Spring
Mệnh đề Switch-case trong java
Mapping Nested Values with Jackson
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Java Program to Solve any Linear Equation in One Variable
Collect a Java Stream to an Immutable Collection
Phương thức forEach() trong java 8
Cơ chế Upcasting và Downcasting trong java
Spring Data MongoDB Transactions
Java Program to Implement Adjacency List
Spring Boot - Service Components
TreeSet và sử dụng Comparable, Comparator trong java