- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
GCD and LCM of two numbers in Java
Following is an example which computes find LCM and GCD of two given numbers.
Program
import java.util.Scanner; public class LCM_GCD { public static void lcm(int a, int b){ int max, step, lcm = 0; if(a > b){ max = step = a; } else{ max = step = b; } while(a!= 0) { if(max%a == 0 && max%b == 0) { lcm = max; break; } max += step; } System.out.println("LCM of given numbers is :: "+lcm); } public static void gcd(int a,int b){ int i, hcf = 0; for(i = 1; i <= a || i <= b; i++) { if( a%i == 0 && b%i == 0 ) hcf = i; } System.out.println("gcd of given two numbers is ::"+hcf); } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter first number ::"); int a = sc.nextInt(); System.out.println("Enter second number ::"); int b = sc.nextInt(); lcm(a, b); gcd(a,b); } }
Output
Enter first number :: 125 Enter second number :: 25 LCM of given numbers is :: 125 GCD of given two numbers is ::25
- Related Articles
- Finding LCM of more than two (or array) numbers without using GCD in C++
- C++ Program to Find the GCD and LCM of n Numbers
- Java Program to Find GCD of two Numbers
- Find GCD of two numbers
- Java Program to Find LCM of two Numbers
- Java program to find the LCM of two numbers
- Find LCM of two numbers
- Java program to find the GCD or HCF of two numbers
- Java Program for GCD of more than two (or array) numbers
- GCD of an array of numbers in java
- Swift Program to Find GCD of two Numbers
- Kotlin Program to Find GCD of two Numbers
- LCM of an array of numbers in Java
- Find any pair with given GCD and LCM in C++
- Program to compute gcd of two numbers recursively in Python

Advertisements