Skip to content

Commit 71ccf32

Browse files
fix(maths): use overflow-safe Euclidean GCD in LeastCommonMultiple (#7795)
* fix(maths): use overflow-safe Euclidean GCD in LeastCommonMultiple * fix(maths): resolve SpotBugs/Infer null checks and expand LCM coverage * fix(maths): remove redundant parentheses and cover null varargs element
1 parent 972969c commit 71ccf32

2 files changed

Lines changed: 226 additions & 27 deletions

File tree

Lines changed: 165 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,181 @@
11
package com.thealgorithms.maths;
22

3+
import java.math.BigInteger;
4+
35
/**
4-
* Is a common mathematics concept to find the smallest value number
5-
* that can be divide using either number without having the remainder.
6-
* https://maticschool.blogspot.com/2013/11/find-least-common-multiple-lcm.html
7-
* @author LauKinHoong
6+
* Provides overflow-safe methods to compute the Least Common Multiple (LCM)
7+
* of integers in {@code O(log(min(a, b)))} time via the Euclidean GCD
8+
* algorithm.
9+
*
10+
* <p>Unlike {@code Math.abs(a * b) / gcd(a, b)}, these methods divide before
11+
* multiplying and throw {@link ArithmeticException} if the exact result
12+
* overflows {@code int} or {@code long}.
13+
*
14+
* @see <a href="https://en.wikipedia.org/wiki/Least_common_multiple">Least common multiple</a>
815
*/
916
public final class LeastCommonMultiple {
17+
1018
private LeastCommonMultiple() {
1119
}
1220

1321
/**
14-
* Finds the least common multiple of two numbers.
22+
* Finds the non-negative least common multiple of two {@code int} values.
1523
*
16-
* @param num1 The first number.
17-
* @param num2 The second number.
18-
* @return The least common multiple of num1 and num2.
24+
* <p>Returns {@code 0} if either {@code num1} or {@code num2} is {@code 0}.
25+
*
26+
* @param num1 the first number
27+
* @param num2 the second number
28+
* @return the least common multiple of {@code num1} and {@code num2}
29+
* @throws ArithmeticException if the exact result overflows {@code int}
1930
*/
2031
public static int lcm(int num1, int num2) {
21-
int high;
22-
int num3;
23-
int cmv = 0;
24-
25-
if (num1 > num2) {
26-
high = num1;
27-
num3 = num1;
28-
} else {
29-
high = num2;
30-
num3 = num2;
31-
}
32-
33-
while (num1 != 0) {
34-
if (high % num1 == 0 && high % num2 == 0) {
35-
cmv = high;
36-
break;
32+
if (num1 == 0 || num2 == 0) {
33+
return 0;
34+
}
35+
long absA = Math.abs((long) num1);
36+
long absB = Math.abs((long) num2);
37+
long gcd = gcdLong(absA, absB);
38+
// absA and absB are at most 2^31, so absA / gcd * absB <= 2^62 < Long.MAX_VALUE.
39+
long result = absA / gcd * absB;
40+
return Math.toIntExact(result);
41+
}
42+
43+
/**
44+
* Finds the non-negative least common multiple of one or more {@code int} values.
45+
*
46+
* <p>Returns {@code 0} if any element in {@code numbers} is {@code 0}.
47+
*
48+
* @param numbers non-empty array of integers
49+
* @return the least common multiple of all elements
50+
* @throws IllegalArgumentException if {@code numbers} is {@code null} or empty
51+
* @throws ArithmeticException if the exact result overflows {@code int}
52+
*/
53+
public static int lcm(int... numbers) {
54+
if (numbers == null || numbers.length == 0) {
55+
throw new IllegalArgumentException("Input array must not be null or empty.");
56+
}
57+
for (int number : numbers) {
58+
if (number == 0) {
59+
return 0;
60+
}
61+
}
62+
int result = Math.toIntExact(Math.abs((long) numbers[0]));
63+
for (int i = 1; i < numbers.length; i++) {
64+
result = lcm(result, numbers[i]);
65+
}
66+
return result;
67+
}
68+
69+
/**
70+
* Finds the non-negative least common multiple of two {@code long} values.
71+
*
72+
* <p>Returns {@code 0L} if either {@code num1} or {@code num2} is {@code 0L}.
73+
*
74+
* @param num1 the first number
75+
* @param num2 the second number
76+
* @return the least common multiple of {@code num1} and {@code num2}
77+
* @throws ArithmeticException if the exact result overflows {@code long}
78+
*/
79+
public static long lcm(long num1, long num2) {
80+
if (num1 == 0L || num2 == 0L) {
81+
return 0L;
82+
}
83+
if (num1 == Long.MIN_VALUE || num2 == Long.MIN_VALUE) {
84+
throw new ArithmeticException("long overflow");
85+
}
86+
long absA = Math.abs(num1);
87+
long absB = Math.abs(num2);
88+
long gcd = gcdLong(absA, absB);
89+
return Math.multiplyExact(absA / gcd, absB);
90+
}
91+
92+
/**
93+
* Finds the non-negative least common multiple of one or more {@code long} values.
94+
*
95+
* <p>Returns {@code 0L} if any element in {@code numbers} is {@code 0L}.
96+
*
97+
* @param numbers non-empty array of {@code long} values
98+
* @return the least common multiple of all elements
99+
* @throws IllegalArgumentException if {@code numbers} is {@code null} or empty
100+
* @throws ArithmeticException if the exact result overflows {@code long}
101+
*/
102+
public static long lcm(long... numbers) {
103+
if (numbers == null || numbers.length == 0) {
104+
throw new IllegalArgumentException("Input array must not be null or empty.");
105+
}
106+
for (long number : numbers) {
107+
if (number == 0L) {
108+
return 0L;
109+
}
110+
}
111+
if (numbers[0] == Long.MIN_VALUE) {
112+
throw new ArithmeticException("long overflow");
113+
}
114+
long result = Math.abs(numbers[0]);
115+
for (int i = 1; i < numbers.length; i++) {
116+
result = lcm(result, numbers[i]);
117+
}
118+
return result;
119+
}
120+
121+
/**
122+
* Finds the non-negative least common multiple of two {@link BigInteger} values.
123+
*
124+
* @param num1 the first number
125+
* @param num2 the second number
126+
* @return the least common multiple of {@code num1} and {@code num2}
127+
* @throws IllegalArgumentException if either argument is {@code null}
128+
*/
129+
public static BigInteger lcm(BigInteger num1, BigInteger num2) {
130+
if (num1 == null || num2 == null) {
131+
throw new IllegalArgumentException("Numbers must not be null.");
132+
}
133+
if (num1.signum() == 0 || num2.signum() == 0) {
134+
return BigInteger.ZERO;
135+
}
136+
BigInteger absA = num1.abs();
137+
BigInteger absB = num2.abs();
138+
return absA.divide(absA.gcd(absB)).multiply(absB);
139+
}
140+
141+
/**
142+
* Finds the non-negative least common multiple of one or more {@link BigInteger} values.
143+
*
144+
* @param numbers non-empty array of non-null {@link BigInteger} values
145+
* @return the least common multiple of all elements
146+
* @throws IllegalArgumentException if {@code numbers} is {@code null}, empty, or contains {@code null}
147+
*/
148+
public static BigInteger lcm(BigInteger... numbers) {
149+
if (numbers == null || numbers.length == 0) {
150+
throw new IllegalArgumentException("Input array must not be null or empty.");
151+
}
152+
boolean hasZero = false;
153+
for (BigInteger number : numbers) {
154+
if (number == null) {
155+
throw new IllegalArgumentException("Elements must not be null.");
37156
}
38-
high += num3;
157+
if (number.signum() == 0) {
158+
hasZero = true;
159+
}
160+
}
161+
if (hasZero) {
162+
return BigInteger.ZERO;
163+
}
164+
BigInteger result = numbers[0].abs();
165+
for (int i = 1; i < numbers.length; i++) {
166+
result = lcm(result, numbers[i]);
167+
}
168+
return result;
169+
}
170+
171+
private static long gcdLong(long a, long b) {
172+
long curA = a;
173+
long curB = b;
174+
while (curB != 0L) {
175+
long remainder = curA % curB;
176+
curA = curB;
177+
curB = remainder;
39178
}
40-
return cmv;
179+
return curA;
41180
}
42181
}

‎src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
package com.thealgorithms.maths;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

6+
import java.math.BigInteger;
7+
import java.util.function.Supplier;
58
import java.util.stream.Stream;
9+
import org.junit.jupiter.api.Test;
610
import org.junit.jupiter.params.ParameterizedTest;
711
import org.junit.jupiter.params.provider.Arguments;
812
import org.junit.jupiter.params.provider.MethodSource;
@@ -16,6 +20,62 @@ void testLcm(int num1, int num2, int expected) {
1620
}
1721

1822
private static Stream<Arguments> provideTestCases() {
19-
return Stream.of(Arguments.of(12, 18, 36), Arguments.of(5, 10, 10), Arguments.of(7, 3, 21), Arguments.of(21, 6, 42), Arguments.of(1, 1, 1), Arguments.of(8, 12, 24), Arguments.of(14, 35, 70), Arguments.of(15, 25, 75), Arguments.of(100, 25, 100), Arguments.of(0, 10, 0));
23+
return Stream.of(Arguments.of(12, 18, 36), Arguments.of(5, 10, 10), Arguments.of(7, 3, 21), Arguments.of(21, 6, 42), Arguments.of(1, 1, 1), Arguments.of(8, 12, 24), Arguments.of(14, 35, 70), Arguments.of(15, 25, 75), Arguments.of(100, 25, 100), Arguments.of(0, 10, 0), Arguments.of(10, 0, 0),
24+
Arguments.of(0, 0, 0), Arguments.of(-12, 18, 36), Arguments.of(12, -18, 36), Arguments.of(-12, -18, 36), Arguments.of(60_000, 90_000, 180_000));
25+
}
26+
27+
@Test
28+
void testIntOverflowThrows() {
29+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(50_000, 50_001));
30+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(Integer.MIN_VALUE, 1));
31+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(1, Integer.MIN_VALUE));
32+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(Integer.MIN_VALUE, 2));
33+
}
34+
35+
@Test
36+
void testIntVarargs() {
37+
assertEquals(24, LeastCommonMultiple.lcm(4, 6, 8, 12));
38+
assertEquals(42, LeastCommonMultiple.lcm(-6, 14, 21));
39+
assertEquals(7, LeastCommonMultiple.lcm(new int[] {-7}));
40+
assertEquals(0, LeastCommonMultiple.lcm(1_000_000_000, 1_000_000_001, 0));
41+
Supplier<int[]> nullIntArray = () -> null;
42+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(nullIntArray.get()));
43+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(new int[] {}));
44+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(new int[] {Integer.MIN_VALUE}));
45+
}
46+
47+
@Test
48+
void testLongLcm() {
49+
assertEquals(6_000_000_000_000L, LeastCommonMultiple.lcm(2_000_000_000_000L, -3_000_000_000_000L));
50+
assertEquals(0L, LeastCommonMultiple.lcm(0L, Long.MAX_VALUE));
51+
assertEquals(0L, LeastCommonMultiple.lcm(Long.MIN_VALUE, 0L));
52+
assertEquals(60L, LeastCommonMultiple.lcm(12L, -15L, 20L));
53+
assertEquals(9L, LeastCommonMultiple.lcm(new long[] {-9L}));
54+
assertEquals(0L, LeastCommonMultiple.lcm(4_000_000_000L, 4_000_000_001L, 0L));
55+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(4_000_000_000L, 4_000_000_001L));
56+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(Long.MIN_VALUE, 1L));
57+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(1L, Long.MIN_VALUE));
58+
Supplier<long[]> nullLongArray = () -> null;
59+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(nullLongArray.get()));
60+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(new long[] {}));
61+
assertThrows(ArithmeticException.class, () -> LeastCommonMultiple.lcm(new long[] {Long.MIN_VALUE}));
62+
}
63+
64+
@Test
65+
void testBigIntegerLcm() {
66+
BigInteger a = BigInteger.valueOf(Long.MAX_VALUE);
67+
BigInteger b = BigInteger.valueOf(Long.MAX_VALUE - 1);
68+
assertEquals(a.multiply(b), LeastCommonMultiple.lcm(a, b));
69+
assertEquals(BigInteger.ZERO, LeastCommonMultiple.lcm(BigInteger.ZERO, a));
70+
assertEquals(BigInteger.ZERO, LeastCommonMultiple.lcm(a, BigInteger.ZERO));
71+
assertEquals(BigInteger.ZERO, LeastCommonMultiple.lcm(BigInteger.ZERO, BigInteger.TEN, BigInteger.valueOf(15)));
72+
assertEquals(BigInteger.valueOf(7), LeastCommonMultiple.lcm(new BigInteger[] {BigInteger.valueOf(-7)}));
73+
assertEquals(BigInteger.valueOf(60), LeastCommonMultiple.lcm(BigInteger.valueOf(12), BigInteger.valueOf(-15), BigInteger.valueOf(20)));
74+
Supplier<BigInteger[]> nullBigArray = () -> null;
75+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm((BigInteger) null, BigInteger.ONE));
76+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(BigInteger.ONE, (BigInteger) null));
77+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(nullBigArray.get()));
78+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(new BigInteger[] {BigInteger.TEN, null}));
79+
assertThrows(IllegalArgumentException.class, () -> LeastCommonMultiple.lcm(new BigInteger[] {}));
2080
}
2181
}

0 commit comments

Comments
 (0)