-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathLCM of 2 numbers
45 lines (35 loc) · 1.27 KB
/
LCM of 2 numbers
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
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.Scanner;
public class LCMCalculator {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the two numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate the LCM
int lcm = calculateLCM(num1, num2);
// Display the LCM
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
// Close the scanner
scanner.close();
};
// Function to calculate the LCM of two numbers
public static int calculateLCM(int num1, int num2) {
// Calculate the GCD using the Euclidean algorithm
int gcd = calculateGCD(num1, num2);
// Calculate the LCM using the formula (a * b) / GCD(a, b)
int lcm = (num1 * num2) / gcd;
return lcm;
};
// Function to calculate the GCD of two numbers using the Euclidean algorithm
public static int calculateGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}