Skip to content

Commit 16bae63

Browse files
Merge branch 'master' into feat/sparse-table
2 parents d028d05 + a1e9429 commit 16bae63

4 files changed

Lines changed: 297 additions & 68 deletions

File tree

‎src/main/java/com/thealgorithms/geometry/ConvexHull.java‎

Lines changed: 28 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package com.thealgorithms.geometry;
22

3+
import java.math.BigInteger;
34
import java.util.ArrayList;
45
import java.util.Collection;
56
import java.util.Collections;
67
import java.util.Comparator;
78
import java.util.HashSet;
9+
import java.util.LinkedHashSet;
810
import java.util.List;
911
import java.util.Set;
1012
import java.util.TreeSet;
@@ -26,7 +28,7 @@ private ConvexHull() {
2628
}
2729

2830
private static boolean checkPointOrientation(Point i, Point j, Point k) {
29-
int detK = Point.orientation(i, j, k);
31+
int detK = orientation(i, j, k);
3032
if (detK > 0) {
3133
return true; // pointsLeftOfIJ
3234
} else if (detK < 0) {
@@ -69,6 +71,7 @@ public static List<Point> convexHullBruteForce(List<Point> points) {
6971
* @return the convex hull points in counter-clockwise order
7072
*/
7173
public static List<Point> convexHullRecursive(List<Point> points) {
74+
points = new ArrayList<>(new LinkedHashSet<>(points));
7275
if (points.size() < 3) {
7376
List<Point> result = new ArrayList<>(points);
7477
Collections.sort(result);
@@ -87,7 +90,7 @@ public static List<Point> convexHullRecursive(List<Point> points) {
8790
List<Point> lowerHull = new ArrayList<>();
8891

8992
for (int i = 1; i < points.size() - 1; i++) {
90-
int det = Point.orientation(leftMostPoint, rightMostPoint, points.get(i));
93+
int det = orientation(leftMostPoint, rightMostPoint, points.get(i));
9194
if (det > 0) {
9295
upperHull.add(points.get(i));
9396
} else if (det < 0) {
@@ -105,14 +108,14 @@ public static List<Point> convexHullRecursive(List<Point> points) {
105108
private static void constructHull(Collection<Point> points, Point left, Point right, Set<Point> convexSet) {
106109
if (!points.isEmpty()) {
107110
Point extremePoint = null;
108-
int extremePointDistance = Integer.MIN_VALUE;
111+
BigInteger extremePointDistance = null;
109112
List<Point> candidatePoints = new ArrayList<>();
110113

111114
for (Point p : points) {
112-
int det = Point.orientation(left, right, p);
113-
if (det > 0) {
115+
BigInteger det = cross(left, right, p);
116+
if (det.signum() > 0) {
114117
candidatePoints.add(p);
115-
if (det > extremePointDistance) {
118+
if (extremePointDistance == null || det.compareTo(extremePointDistance) > 0) {
116119
extremePointDistance = det;
117120
extremePoint = p;
118121
}
@@ -154,54 +157,38 @@ private static List<Point> sortCounterClockwise(List<Point> hullPoints) {
154157
sorted.remove(finalPivot);
155158

156159
sorted.sort((p1, p2) -> {
157-
int crossProduct = Point.orientation(finalPivot, p1, p2);
158-
159-
if (crossProduct == 0) {
160-
// Collinear points: sort by distance from pivot (closer first for convex hull)
161-
long dist1 = distanceSquared(finalPivot, p1);
162-
long dist2 = distanceSquared(finalPivot, p2);
163-
return Long.compare(dist1, dist2);
164-
}
160+
int crossProduct = orientation(finalPivot, p1, p2);
165161

166162
// Positive cross product means p2 is counter-clockwise from p1
167163
// We want counter-clockwise order, so if p2 is CCW from p1, p1 should come first
168164
return -crossProduct;
169165
});
170166

171-
// Build result with pivot first, filtering out intermediate collinear points
167+
// Hull vertices are strictly convex, so no two of them are collinear with the pivot.
172168
List<Point> result = new ArrayList<>();
173169
result.add(finalPivot);
174-
175-
if (!sorted.isEmpty()) {
176-
// This loop iterates through the points sorted by angle.
177-
// For points that are collinear with the pivot, we only want the one that is farthest away.
178-
// The sort places closer points first.
179-
for (int i = 0; i < sorted.size() - 1; i++) {
180-
// Check the orientation of the pivot, the current point, and the next point.
181-
int orientation = Point.orientation(finalPivot, sorted.get(i), sorted.get(i + 1));
182-
183-
// If the orientation is not 0, it means the next point (i+1) is at a new angle.
184-
// Therefore, the current point (i) must be the farthest point at its angle. We keep it.
185-
if (orientation != 0) {
186-
result.add(sorted.get(i));
187-
}
188-
// If the orientation is 0, the points are collinear. We discard the current point (i)
189-
// because it is closer to the pivot than the next point (i+1).
190-
}
191-
// Always add the very last point from the sorted list. It is either the only point
192-
// at its angle, or it's the farthest among a set of collinear points.
193-
result.add(sorted.getLast());
194-
}
170+
result.addAll(sorted);
195171

196172
return result;
197173
}
198174

199175
/**
200-
* Computes the squared distance between two points to avoid floating point operations.
176+
* Cross product of (b - a) and (c - a), computed exactly. The coordinate differences are
177+
* widened to long before they are multiplied, and the products can still be larger than a
178+
* long, so BigInteger is used.
179+
*/
180+
private static BigInteger cross(Point a, Point b, Point c) {
181+
BigInteger abx = BigInteger.valueOf((long) b.x() - a.x());
182+
BigInteger aby = BigInteger.valueOf((long) b.y() - a.y());
183+
BigInteger acx = BigInteger.valueOf((long) c.x() - a.x());
184+
BigInteger acy = BigInteger.valueOf((long) c.y() - a.y());
185+
return abx.multiply(acy).subtract(aby.multiply(acx));
186+
}
187+
188+
/**
189+
* Sign of the cross product of (b - a) and (c - a): positive when c is left of the line from a to b.
201190
*/
202-
private static long distanceSquared(Point p1, Point p2) {
203-
long dx = (long) p1.x() - p2.x();
204-
long dy = (long) p1.y() - p2.y();
205-
return dx * dx + dy * dy;
191+
private static int orientation(Point a, Point b, Point c) {
192+
return cross(a, b, c).signum();
206193
}
207194
}
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/geometry/ConvexHullTest.java‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,47 @@ void testRecursiveHullForCoverage() {
135135
assertEquals(expectedCollinear, resultCollinear, "Should correctly handle collinear points on the hull edge");
136136
assertTrue(isCounterClockwise(resultCollinear), "The result of the collinear test should be in counter-clockwise order");
137137
}
138+
@Test
139+
void testConvexHullRecursiveExcludesInteriorPoints() {
140+
// (1,8) is strictly inside the hull of the other four points.
141+
List<Point> points = new ArrayList<>(List.of(new Point(1, 5), new Point(1, 8), new Point(2, 9), new Point(0, 10), new Point(4, 19)));
142+
List<Point> expected = List.of(new Point(1, 5), new Point(2, 9), new Point(4, 19), new Point(0, 10));
143+
assertEquals(expected, ConvexHull.convexHullRecursive(points));
144+
145+
// (7,2) and (8,3) are strictly inside the triangle (4,0), (11,3), (3,10).
146+
List<Point> points2 = new ArrayList<>(List.of(new Point(4, 0), new Point(7, 2), new Point(8, 3), new Point(11, 3), new Point(3, 10)));
147+
List<Point> expected2 = List.of(new Point(4, 0), new Point(11, 3), new Point(3, 10));
148+
assertEquals(expected2, ConvexHull.convexHullRecursive(points2));
149+
}
150+
151+
@Test
152+
void testConvexHullRecursiveDuplicatePoints() {
153+
List<Point> points = new ArrayList<>(List.of(new Point(5, 5), new Point(5, 5)));
154+
List<Point> expected = List.of(new Point(5, 5));
155+
assertEquals(expected, ConvexHull.convexHullRecursive(points));
156+
}
157+
158+
@Test
159+
void testConvexHullRecursiveLargeCoordinates() {
160+
// Differences between these coordinates overflow int when multiplied.
161+
List<Point> points = new ArrayList<>(List.of(new Point(-32768, -32768), new Point(32768, -32768), new Point(-32768, 32768)));
162+
List<Point> expected = List.of(new Point(-32768, -32768), new Point(32768, -32768), new Point(-32768, 32768));
163+
assertEquals(expected, ConvexHull.convexHullRecursive(points));
164+
}
165+
166+
@Test
167+
void testConvexHullRecursiveFullIntRange() {
168+
int min = Integer.MIN_VALUE;
169+
int max = Integer.MAX_VALUE;
170+
// Square corners, one point on a corner-to-corner diagonal and one inside.
171+
List<Point> points = new ArrayList<>(List.of(new Point(min, min), new Point(max, min), new Point(max, max), new Point(min, max), new Point(0, 0), new Point(min, 0), new Point(max, 0), new Point(0, max)));
172+
List<Point> expected = List.of(new Point(min, min), new Point(max, min), new Point(max, max), new Point(min, max));
173+
assertEquals(expected, ConvexHull.convexHullRecursive(points));
174+
}
175+
176+
@Test
177+
void testConvexHullBruteForceLargeCoordinates() {
178+
List<Point> points = new ArrayList<>(List.of(new Point(-32768, -32768), new Point(32768, -32768), new Point(-32768, 32768)));
179+
assertEquals(3, ConvexHull.convexHullBruteForce(points).size());
180+
}
138181
}

0 commit comments

Comments
 (0)