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 Represent Linear Equations in Matrix Form
Java Program to Implement Hash Tables chaining with Singly Linked Lists
Guide to the Java Queue Interface
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Java Program to Print only Odd Numbered Levels of a Tree
Java Program to Implement Interval Tree
Java Program to Implement Naor-Reingold Pseudo Random Function
Java Program to Implement Tarjan Algorithm
New Features in Java 12
Spring JDBC
Java Program to Find kth Largest Element in a Sequence
Map to String Conversion in Java
Java Program to Create a Random Graph Using Random Edge Generation
Spring Boot - Cloud Configuration Client
Guide to Guava Multimap
Java Program to Implement WeakHashMap API
A Guide to Java HashMap
The Java 8 Stream API Tutorial
Array to String Conversions
Java Program to Find Inverse of a Matrix
Zipping Collections in Java
Java Program to Implement Lloyd’s Algorithm
Sắp xếp trong Java 8
Spring Boot - CORS Support
Java Program to Check if a Matrix is Invertible
Java Program to Implement Stack using Two Queues
Rate Limiting in Spring Cloud Netflix Zuul
How to Read a Large File Efficiently with Java
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Show Hibernate/JPA SQL Statements from Spring Boot
Intro to Inversion of Control and Dependency Injection with Spring
Java – Reader to InputStream