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 Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Java – Reader to InputStream
Java Program to Perform Quick Sort on Large Number of Elements
A Guide to BitSet in Java
Java Program to Implement Karatsuba Multiplication Algorithm
How to Change the Default Port in Spring Boot
Introduction to Spring Method Security
Java Program to Implement Miller Rabin Primality Test Algorithm
Java Program to Implement Adjacency Matrix
Java Program to Find Number of Articulation points in a Graph
Getting Started with Stream Processing with Spring Cloud Data Flow
Tạo số và chuỗi ngẫu nhiên trong Java
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Collect a Java Stream to an Immutable Collection
JUnit5 @RunWith
Java – Write to File
A Comparison Between Spring and Spring Boot
Hướng dẫn Java Design Pattern – Null Object
Java Program to Implement ArrayList API
JPA/Hibernate Persistence Context
Jackson Date
Send an email with an attachment
Tạo chương trình Java đầu tiên sử dụng Eclipse
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Prevent Brute Force Authentication Attempts with Spring Security
Jackson – Unmarshall to Collection/Array
Binary Numbers in Java
Model, ModelMap, and ModelAndView in Spring MVC
Java Program to Implement AVL Tree
Java Program for Douglas-Peucker Algorithm Implementation
Spring Data MongoDB – Indexes, Annotations and Converters