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 Implement Attribute API
A Guide To UDP In Java
Spring Boot Configuration with Jasypt
Hướng dẫn Java Design Pattern – Transfer Object
Java program to Implement Tree Set
Introduction to Spring Data REST
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Java Program to Implement the One Time Pad Algorithm
Spring Boot Gradle Plugin
Guide to Spring @Autowired
Java Program to Implement Graph Coloring Algorithm
Spring Webflux with Kotlin
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Hướng dẫn Java Design Pattern – Intercepting Filter
Java toString() Method
Sorting Query Results with Spring Data
Java Program to Find Transitive Closure of a Graph
Hướng dẫn Java Design Pattern – Observer
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Spring Data – CrudRepository save() Method
Guide to Mustache with Spring Boot
Java Program to Find the Edge Connectivity of a Graph
Introduction to the Functional Web Framework in Spring 5
Java Program to Implement Repeated Squaring Algorithm
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
Java InputStream to Byte Array and ByteBuffer
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Spring Boot - Rest Template
JUnit 5 @Test Annotation
How to Use if/else Logic in Java 8 Streams
Hướng dẫn sử dụng Java Annotation