Here, we will write a program to calculate the LCM of two numbers in java. LCM stands for Lowest Common Factor. The Numbers will be taken as input from the user using the scanner class.
Before we start, click on the links below to have a proper working idea of the if statement and break statement that this program uses.
Program to Find the LCM of Two Numbers in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //find the lcm of two number in java import java.util.Scanner; public class LCM { public static void main(String[] args) { int num1, num2, lcm; Scanner s = new Scanner(System.in); System.out.print("Enter the first number: "); num1 = s.nextInt(); Scanner sc = new Scanner(System.in); System.out.print("Enter the second number: "); num2 = sc.nextInt(); // maximum number between n1 and n2 is stored in lcm lcm = (num1 > num2) ? num1 : num2; 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: 81
Enter the second number: 27
The LCM of 81 and 27 is 81.