Java Code to find LCM ( Least Common Multiple) Example Code

Least Common Multiples is smallest positive integer which is a multiple of both numbers . The following code illustrates how to find Least Common Multiple (LCM) of two Numbers (a,b) which are passed through command line .

For example, consider 21 , 6

Multiples of 21 are 21, 42, 63, 84, 105, ….

Multiples of 6 are 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84 …..

Common Multiples of (21, 6) are 42, 84 . So Least Common Multiple is 42

Example 2 : Consider 4, 6

Multiples of 4 are 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68 …

Multiples of 6 are 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84 …..

Common Multiples of (21, 6) are 12, 36, 60. So Least Common Multiple is 12

The following code accepts two numbers from command line and finds LCM

 


package com.javaonline;

import java.util.Scanner;

class LCM {
public static void main(String[] args) {

int a=0, b=0;

if (args.length!=2)
{
System.out.println("invalid input");
System.exit(0);

}

try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
}
catch (Exception e)
{
System.out.println("Input Error . input format -> java GCD number1 number2. eg. java GCD 24 54 ");
System.exit(0);
}
int lcm=LCM(a,b);
System.out.println(" LCM("+ a + "," + b + ") " +"is " + lcm);
int lcm1=LCM1(a,b);
System.out.println(" Using Loop LCM("+ a + "," + b + ") " +"is " + lcm1);

}
// Finding GCD using Loop

public static int LCM(int a,int b)
{
int lcm = a/GCD(a,b) * b;
return lcm;

}

// Using Loop
public static int LCM1(int a,int b)
{
for(int n=1;;n++)
{
if(n%a == 0 && n%b == 0) return n;
}
}

// Finding GCD using Recursion

public static int GCD(int a, int b) {

if (b==0) return a; else return GCD(b, a % b);
}

} 

 

Runnig the above program

java LCM 48 180

LCM(48,180) is 720

Using Loop LCM(48,180) is 720

java LCM 4 6

LCM(4,6) is 12

Using Loop LCM(4,6) is 12

java LCM 21 6

LCM(21,6) is 42

Using Loop LCM(21,6) is 42

 

You may also like

Leave a Reply