Java Program to Find LCM of a Two Given Number

Java Program to Find LCM of a Two Given Number thumbnail
20K
By Dhiraj Ray 14 January, 2018

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

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.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.