File tree Expand file tree Collapse file tree
src/main/java/com/williamfiset/algorithms/math Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -250,7 +250,7 @@ $ java -cp classes com.williamfiset.algorithms.search.BinarySearch
250250- [ Fast Fourier transform (quick polynomial multiplication, complex numbers)] ( src/main/java/com/williamfiset/algorithms/math/FastFourierTransformComplexNumbers.java ) ** - O(nlog(n))**
251251- [ Primality check] ( src/main/java/com/williamfiset/algorithms/math/IsPrime.java ) ** - O(√n)**
252252- [ Primality check (Rabin-Miller)] ( src/main/java/com/williamfiset/algorithms/math/RabinMillerPrimalityTest.py ) ** - O(k)**
253- - [ Least Common Multiple (LCM)] ( src/main/java/com/williamfiset/algorithms/math/LCM .java ) ** - ~ O(log(a + b))**
253+ - [ Least Common Multiple (LCM)] ( src/main/java/com/williamfiset/algorithms/math/Lcm .java ) ** - ~ O(log(a + b))**
254254- [ Modular inverse] ( src/main/java/com/williamfiset/algorithms/math/ModularInverse.java ) ** - ~ O(log(a + b))**
255255- [ Prime factorization (pollard rho)] ( src/main/java/com/williamfiset/algorithms/math/PrimeFactorization.java ) ** - O(n<sup >1/4</sup >)**
256256- [ Relatively prime check (coprimality check)] ( src/main/java/com/williamfiset/algorithms/math/RelativelyPrime.java ) ** - ~ O(log(a + b))**
Original file line number Diff line number Diff line change @@ -49,10 +49,10 @@ java_binary(
4949 runtime_deps = [":math" ],
5050)
5151
52- # bazel run //src/main/java/com/williamfiset/algorithms/math:LCM
52+ # bazel run //src/main/java/com/williamfiset/algorithms/math:Lcm
5353java_binary (
54- name = "LCM " ,
55- main_class = "com.williamfiset.algorithms.math.LCM " ,
54+ name = "Lcm " ,
55+ main_class = "com.williamfiset.algorithms.math.Lcm " ,
5656 runtime_deps = [":math" ],
5757)
5858
Load Diff This file was deleted.
Original file line number Diff line number Diff line change 1+ /**
2+ * Computes the Least Common Multiple (LCM) of two numbers using the relation LCM(a, b) = |a /
3+ * gcd(a, b) * b|.
4+ *
5+ * <p>Time: ~O(log(a + b))
6+ *
7+ * @author William Fiset, william.alexandre.fiset@gmail.com
8+ */
9+ package com .williamfiset .algorithms .math ;
10+
11+ public class Lcm {
12+
13+ /** Returns the least common multiple of a and b. The result is always non-negative. */
14+ public static long lcm (long a , long b ) {
15+ return Math .abs (a / gcd (a , b ) * b );
16+ }
17+
18+ private static long gcd (long a , long b ) {
19+ if (b == 0 )
20+ return Math .abs (a );
21+ return gcd (b , a % b );
22+ }
23+
24+ public static void main (String [] args ) {
25+ System .out .println (lcm (12 , 18 )); // 36
26+ System .out .println (lcm (-12 , 18 )); // 36
27+ System .out .println (lcm (12 , -18 )); // 36
28+ System .out .println (lcm (-12 , -18 )); // 36
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments