diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index 5156e4ac881d..df27516367b2 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -1,9 +1,23 @@ package com.thealgorithms.maths; /** - * This is Euclid's algorithm, used to find the greatest common - * denominator Override function name gcd + * This class provides methods to compute the Greatest Common Divisor (GCD) of two or more integers. * + * The Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that divides each of the integers without leaving a remainder. + * + * The GCD can be computed using the Euclidean algorithm, which is based on the principle that the GCD of two numbers also divides their difference. + * + * For more information, refer to the + * Greatest Common Divisor Wikipedia page. + * + * Example usage: + *
+ * int result1 = GCD.gcd(48, 18);
+ * System.out.println("GCD of 48 and 18: " + result1); // Output: 6
+ *
+ * int result2 = GCD.gcd(48, 18, 30);
+ * System.out.println("GCD of 48, 18, and 30: " + result2); // Output: 6
+ *
* @author Oskar Enmalm 3/10/17
*/
public final class GCD {
@@ -40,7 +54,7 @@ public static int gcd(int num1, int num2) {
* @param numbers the input array
* @return gcd of all of the numbers in the input array
*/
- public static int gcd(int[] numbers) {
+ public static int gcd(int... numbers) {
int result = 0;
for (final var number : numbers) {
result = gcd(result, number);
@@ -48,12 +62,4 @@ public static int gcd(int[] numbers) {
return result;
}
-
- public static void main(String[] args) {
- int[] myIntArray = {4, 16, 32};
-
- // call gcd function (input array)
- System.out.println(gcd(myIntArray)); // => 4
- System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
- }
}
diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java
index 5a659664fd29..bac3f8f7596c 100644
--- a/src/test/java/com/thealgorithms/maths/GCDTest.java
+++ b/src/test/java/com/thealgorithms/maths/GCDTest.java
@@ -40,6 +40,11 @@ void test7() {
Assertions.assertEquals(GCD.gcd(9, 6), 3);
}
+ @Test
+ void test8() {
+ Assertions.assertEquals(GCD.gcd(48, 18, 30, 12), 6);
+ }
+
@Test
void testArrayGcd1() {
Assertions.assertEquals(GCD.gcd(new int[] {9, 6}), 3);