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:
RegEx for matching Date Pattern in Java
So sánh ArrayList và LinkedList trong Java
Serialization và Deserialization trong java
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Fixing 401s with CORS Preflights and Spring Security
Working with Kotlin and JPA
Java Program to Implement Splay Tree
Java IO vs NIO
Request Method Not Supported (405) in Spring
Java Program to Implement Euclid GCD Algorithm
Java Program to Perform Insertion in a BST
Comparing Arrays in Java
Calling Stored Procedures from Spring Data JPA Repositories
Java Program to Implement Queue
How to Find an Element in a List with Java
Java Program to Perform Cryptography Using Transposition Technique
Chuyển đổi giữa các kiểu dữ liệu trong Java
Guide to Mustache with Spring Boot
Java Program to Implement Patricia Trie
Java Program to Implement SynchronosQueue API
Java Program to Generate Random Hexadecimal Byte
Spring Security 5 – OAuth2 Login
Introduction to Using Thymeleaf in Spring
Spring Boot - Hystrix
Spring Data JPA @Query
Find the Registered Spring Security Filters
Adding Parameters to HttpClient Requests
Java Program to Solve Tower of Hanoi Problem using Stacks
Comparing Dates in Java
Tạo ứng dụng Java RESTful Client với thư viện OkHttp
Java Program to Implement ConcurrentLinkedQueue API
LinkedHashSet trong Java hoạt động như thế nào?