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:
The StackOverflowError in Java
Generating Random Numbers in a Range in Java
Java Program to Implement vector
Constructor Dependency Injection in Spring
Java Program to Implement Nth Root Algorithm
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Spring Boot - Scheduling
Lập trình mạng với java
Hướng dẫn Java Design Pattern – MVC
Apache Commons Collections BidiMap
Hướng dẫn sử dụng Java Generics
Java IO vs NIO
Java Collections Interview Questions
Hướng dẫn Java Design Pattern – Adapter
Removing all Nulls from a List in Java
OAuth2 Remember Me with Refresh Token
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Copy a List to Another List in Java
Java Program to Implement Park-Miller Random Number Generation Algorithm
Collect a Java Stream to an Immutable Collection
Java Convenience Factory Methods for Collections
String Initialization in Java
Introduction to Spring Cloud OpenFeign
Luồng Daemon (Daemon Thread) trong Java
Spring REST API + OAuth2 + Angular
Java Program to Generate Date Between Given Range
Java Program to Implement Kosaraju Algorithm
Java Program to Represent Graph Using Incidence Matrix
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?
Hướng dẫn sử dụng luồng vào ra ký tự trong Java
Sorting Query Results with Spring Data