forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LCM.java
29 lines (25 loc) · 772 Bytes
/
LCM.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
/**
* An implementation of finding the LCM of two numbers
*
* <p>Time Complexity ~O(log(a + b))
*
* @author William Fiset, [email protected]
*/
package com.williamfiset.algorithms.math;
public class LCM {
// Finds the greatest common divisor of a and b
private static long gcd(long a, long b) {
return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b);
}
// Finds the least common multiple of a and b
public static long lcm(long a, long b) {
long lcm = (a / gcd(a, b)) * b;
return lcm > 0 ? lcm : -lcm;
}
public static void main(String[] args) {
System.out.println(lcm(12, 18)); // 36
System.out.println(lcm(-12, 18)); // 36
System.out.println(lcm(12, -18)); // 36
System.out.println(lcm(-12, -18)); // 36
}
}