Skip to content

Commit e14b30b

Browse files
authored
Fix empty input handling in GCD (TheAlgorithms#4199)
1 parent 36232a8 commit e14b30b

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

src/main/java/com/thealgorithms/maths/GCD.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,15 @@ public static int gcd(int num1, int num2) {
3333
}
3434

3535
/**
36-
* get greatest common divisor in array
36+
* @brief computes gcd of an array of numbers
3737
*
38-
* @param number contains number
39-
* @return gcd
38+
* @param numbers the input array
39+
* @return gcd of all of the numbers in the input array
4040
*/
41-
public static int gcd(int[] number) {
42-
int result = number[0];
43-
for (int i = 1; i < number.length; i++) { // call gcd function (input two value)
44-
result = gcd(result, number[i]);
41+
public static int gcd(int[] numbers) {
42+
int result = 0;
43+
for (final var number : numbers) {
44+
result = gcd(result, number);
4545
}
4646

4747
return result;

src/test/java/com/thealgorithms/maths/GCDTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,19 @@ void test6() {
4848
void test7() {
4949
Assertions.assertEquals(GCD.gcd(9, 6), 3);
5050
}
51+
52+
@Test
53+
void testArrayGcd1() {
54+
Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3);
55+
}
56+
57+
@Test
58+
void testArrayGcd2() {
59+
Assertions.assertEquals(GCD.gcd(new int[]{2*3*5*7, 2*5*5*5, 2*5*11, 5*5*5*13}), 5);
60+
}
61+
62+
@Test
63+
void testArrayGcdForEmptyInput() {
64+
Assertions.assertEquals(GCD.gcd(new int[]{}), 0);
65+
}
5166
}

0 commit comments

Comments
 (0)