Beginners Programs :

LCM Of Two Numbers Java Program | 5 Ways – Programs

Java program to find the LCM of two numbers – In the below-mentioned java programs, we discuss the various methods to evaluate the LCM of the two given numbers such as using Static Method, Command Line Arguments and Recursion. We also have added the compiler to each and every program along with sample outputs with specific examples.

What is LCM:

Least Common Multiplier or LCM of any n numbers is the least value that is a multiple of the given numbers.

For example:

Let us take three numbers such as 12, 15 and 18.

  • 12 = 2 * 2 * 3
  • 15 = 3 * 5
  • 18 = 2 * 3 * 3

So we take the common prime factors and then the rest of the ones and multiply them with each other which would give us the LCM.

LCM = 2 * 2 * 3 * 3 * 5 = 180

Java program LCM of two numbers

Using Static Method

1) Read the values a,b using scanner object as sc.nextInt() and store these values in the variables a,b. In this program called the static method lcmCalculation(a,b) in the main method, lcmCalculation(a,b) will calculate the lcm of two numbers.

2) The a,b values passed to n1 , n2 ,then checks the if condition ,n1>n2 then res=n1 otherwise res=n2. temp initialized to res, until the condition (res%n1!=0 || res%n2!=0) is false ,it calculates the res=temp*i;, increases the i value by 1, returns the result value.

Output:

LCM Of Two Numbers – Using Command Line Arguments

1) The values we will pass at run-time are called command line arguments, will store at string array “String args[]” of the main method.

2) We are converting the string present at the args[0], in to long using the wrapper class “Long”, and method parseLong() and the value will store it in the variable n1.

3) We are converting the string present at the args[1], in to long using the wrapper class “Long”, and method parseLong() and the value will store it in the variable n2.

4) Checks the if condition if n1>n2 then lcm=n1 otherwise lcm=n2 and b assigned with lcm, while loop will calculate the lcm=b*i until the condition is false.

Output:

Finding LCM of n numbers

Output:

Using Recursion Method

1) In this program, lcmCal(long n1,long n2,long temp,long res) method calls itself as lcmCal(n1,n2,temp,res), repeats until if condition is false ,then returns the value res.

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *

*