Java Program to Find LCM of a Two Given Number
Description
Write a Java program to find LCM of given two numbers.LCM stands for Lowest Common Multiple. LCM of a two given number a and b is the smallest positive integer that is divisible by both a and b.For example the LCM of 4 and 6 is 12. Following is the java program to find LCM using while and for loop.
LCM.java(Using While Loop)package com.devglan; public class LCM { public int findLCM(int a, int b){ int lcm = (a > b) ? a : b; while(true){ if (lcm % a == 0 && lcm % b == 0) { break; } lcm++; } return lcm; } public static void main(String [] args){ LCM lcm = new LCM(); System.out.println("LCM Of "+ 4 +" and " + 6 + " is : " + lcm.findLCM(4,6)); } }Using For Loop
public int findLCM(int a, int b){ int lcm = (a > b) ? a : b; for(; lcm <= (a * b) ; lcm++){ if (lcm % a == 0 && lcm % b == 0) { break; } } return lcm; }
Explanation
Click to Suggest Your Own Explanation
As LCM is lowest common multiple and hence the lcm of a and b must be greater then a and b and less then or equal to a*b. That's why with while loop start a loop with the highest number between the two given number and continue till you find the common multiple of both the numbers i.e. the number which is exactly divisible by both the numbers. Once, this number is identified break the loop and exit. But in case of for loop as LCM of a and b will be always less then or equal to a*b, the end limit for the loop will be a*b.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.