Fix empty input handling in GCD (#4199)

This commit is contained in:
Piotr Idzik 2023-05-27 16:58:56 +02:00 committed by GitHub
parent 36232a8373
commit e14b30b88c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 7 deletions

View File

@ -33,15 +33,15 @@ public class GCD {
} }
/** /**
* get greatest common divisor in array * @brief computes gcd of an array of numbers
* *
* @param number contains number * @param numbers the input array
* @return gcd * @return gcd of all of the numbers in the input array
*/ */
public static int gcd(int[] number) { public static int gcd(int[] numbers) {
int result = number[0]; int result = 0;
for (int i = 1; i < number.length; i++) { // call gcd function (input two value) for (final var number : numbers) {
result = gcd(result, number[i]); result = gcd(result, number);
} }
return result; return result;

View File

@ -48,4 +48,19 @@ public class GCDTest {
void test7() { void test7() {
Assertions.assertEquals(GCD.gcd(9, 6), 3); Assertions.assertEquals(GCD.gcd(9, 6), 3);
} }
@Test
void testArrayGcd1() {
Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3);
}
@Test
void testArrayGcd2() {
Assertions.assertEquals(GCD.gcd(new int[]{2*3*5*7, 2*5*5*5, 2*5*11, 5*5*5*13}), 5);
}
@Test
void testArrayGcdForEmptyInput() {
Assertions.assertEquals(GCD.gcd(new int[]{}), 0);
}
} }