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:
A Guide to the finalize Method in Java
Java Program to implement Sparse Vector
Java Program to Implement Vector API
The DAO with Spring and Hibernate
Wiring in Spring: @Autowired, @Resource and @Inject
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Concurrency Interview Questions and Answers
Java Program to Implement Affine Cipher
Spring Cloud AWS – EC2
Java Program to Implement IdentityHashMap API
JPA/Hibernate Persistence Context
Java – Delete a File
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
Java Program to Convert a Decimal Number to Binary Number using Stacks
Iterating over Enum Values in Java
Java Program to Implement Quick Sort Using Randomization
Date Time trong Java 8
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Hướng dẫn Java Design Pattern – Composite
Java Program to Implement CopyOnWriteArrayList API
Calling Stored Procedures from Spring Data JPA Repositories
Hướng dẫn Java Design Pattern – Service Locator
Spring WebClient and OAuth2 Support
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Spring Boot - Twilio
Guide to the Synchronized Keyword in Java
Java Scanner hasNext() vs. hasNextLine()
Quick Guide to java.lang.System
Java Program to Implement Insertion Sort
Java Program to Implement Network Flow Problem
Java IO vs NIO
Một số từ khóa trong Java