;

Java Program to Find LCM of Two Numbers


Tutorialsrack 25/05/2021 Java

In this Java program, you'll learn how to find the LCM of two numbers. This is done using for, while loops and using GCD in Java.

What is LCM?

The LCM of the two numbers is the smallest positive integer that is divisible by both the given numbers. For example, the L.C.M. of 5 and 6 is 30.

Here is the code of the program to find the LCM(Least Common Multiple) of two numbers.

Example 1: Java Program to Find the LCM using if..else statement and while Loop

Example 1: Java Program to Find the LCM using if..else statement and while Loop
// Java Program to Find LCM of Two Numbers using If..Else and While Loop
 
import java.util.Scanner;
 
public class JavaPrograms {
 
	public static void main(String[] args) {
 
		int lcm;
		// scanner class declaration
		Scanner sc = new Scanner(System.in);
		// input from the user
		System.out.print("Enter the first number : ");
		int num1 = sc.nextInt();
		// input from the user
		System.out.print("Enter the second number : ");
		int num2 = sc.nextInt();
		
		// closing scanner class(not compulsory, but good programming practice)
		sc.close();
 
	    // maximum number between n1 and n2 is stored in LCM
	    lcm = (num1 > num2) ? num1 : num2;
 
	    // Always true
	    while(true) {
	      if( lcm % num1 == 0 && lcm % num2 == 0 ) {
	        System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);
	        break;
	      }
	      ++lcm;
	    }
 
	}
}
Output

Enter the first number : 48

Enter the second number : 18

The LCM of 48 and 18 is 144.

Example 2: Java Program to Find LCM of Two Numbers using GCD

Java Program to Find HCF or GCD of Two Numbers

Example 2: Java Program to Find LCM of Two Numbers using GCD
// Java Program to Find LCM of Two Numbers using GCD

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {

		int lcm, gcd = 1;
		// scanner class declaration
		Scanner sc = new Scanner(System.in);
		// input from the user
		System.out.print("Enter the first number : ");
		int num1 = sc.nextInt();
		// input from the user
		System.out.print("Enter the second number : ");
		int num2 = sc.nextInt();

		// closing scanner class(not compulsory, but good programming practice)
		sc.close();

		for (int i = 1; i <= num1 && i <= num2; ++i) {
			// Checks if i is factor of both integers
			if (num1 % i == 0 && num2 % i == 0)
				gcd = i;
		}

		lcm = (num1 * num2) / gcd;
		System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);

	}
}
Output

Enter the first number : 48

Enter the second number : 18

The LCM of 48 and 18 is 144.


Related Posts



Comments

Recent Posts
Tags