From e14b30b88c0de95186fe1937f795b7d8fd3fa8aa Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 27 May 2023 16:58:56 +0200 Subject: [PATCH] Fix empty input handling in GCD (#4199) --- src/main/java/com/thealgorithms/maths/GCD.java | 14 +++++++------- .../java/com/thealgorithms/maths/GCDTest.java | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index c05f9633..96a2b47d 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -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 - * @return gcd + * @param numbers the input array + * @return gcd of all of the numbers in the input array */ - public static int gcd(int[] number) { - int result = number[0]; - for (int i = 1; i < number.length; i++) { // call gcd function (input two value) - result = gcd(result, number[i]); + public static int gcd(int[] numbers) { + int result = 0; + for (final var number : numbers) { + result = gcd(result, number); } return result; diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java index e18d3ea8..bbf10cad 100644 --- a/src/test/java/com/thealgorithms/maths/GCDTest.java +++ b/src/test/java/com/thealgorithms/maths/GCDTest.java @@ -48,4 +48,19 @@ public class GCDTest { void test7() { 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); + } }