Java Program - Find LCM of Two Numbers without GCD
LCM stands for Least Common Multiple. The LCM of two numbers is the smallest number that can be divided by both numbers.
For example - LCM of 20 and 25 is 100 and LCM of 30 and 40 is 120.
The approach is to start with the largest of the two numbers and keep incrementing the larger number by itself till it becomes divisible by the smaller number.
Example: find LCM of two numbers without GCD
In the example below, to calculate the LCM of two numbers, largest of the two numbers is increased by itself till it becomes divisible by the smaller number.
public class MyClass { static int lcm(int x, int y) { int i, large, small; large = Math.max(x, y); small = Math.min(x, y); i = large; while (true) { if(i % small == 0) return i; i = i + large; } } public static void main(String[] args) { int x = 30; int y = 40; System.out.println("LCM of "+ x +" and "+ y +" is: "+ lcm(x,y)); } }
The above code will give the following output:
LCM of 30 and 40 is: 120
Recommended Pages
- Java Program - To Check Prime Number
- Java Program - Bubble Sort
- Java Program - Selection Sort
- Java Program - Maximum Subarray Sum
- Java Program - Reverse digits of a given Integer
- Java - Swap two numbers
- Java Program - Fibonacci Sequence
- Java Program - Insertion Sort
- Java Program - Find Factorial of a Number
- Java Program - Find HCF of Two Numbers
- Java Program - Merge Sort
- Java Program - Shell Sort
- Stack in Java
- Queue in Java
- Java Program - Find LCM of Two Numbers
- Java Program - To Check Armstrong Number
- Java Program - Counting Sort
- Java Program - Radix Sort
- Java Program - Find Largest Number among Three Numbers
- Java Program - Print Floyd's Triangle