-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP15_GCDandLCM.java
More file actions
45 lines (40 loc) · 1.33 KB
/
Copy pathP15_GCDandLCM.java
File metadata and controls
45 lines (40 loc) · 1.33 KB
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
package programs;
/**
* ============================================================
* PROGRAM 15: GCD (HCF) and LCM Calculator
* ============================================================
* Problem: WAP to find the Greatest Common Divisor (GCD) and
* Least Common Multiple (LCM) of two numbers using the Euclidean algorithm.
* - Formula: GCD(a, b) = GCD(b, a % b)
* - Formula: LCM(a, b) = (a * b) / GCD(a, b)
* ============================================================
*/
public class P15_GCDandLCM {
public static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return Math.abs(a);
}
public static long findLCM(int a, int b) {
if (a == 0 || b == 0) return 0;
return (Math.abs((long) a * b)) / findGCD(a, b);
}
public static void main(String[] args) {
int[][] pairs = {
{48, 18},
{60, 48},
{12, 15},
{100, 25},
{17, 19} // coprime
};
System.out.println("=== GCD AND LCM TESTS ===");
for (int[] pair : pairs) {
int a = pair[0], b = pair[1];
System.out.printf(" Numbers: (%3d, %3d) -> GCD: %2d | LCM: %4d%n",
a, b, findGCD(a, b), findLCM(a, b));
}
}
}