Skip to content

Improvement: Removed main function from GCD class . Corrected and improved docstring. #5828

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions src/main/java/com/thealgorithms/maths/GCD.java
Original file line number Diff line number Diff line change
@@ -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
* <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">Greatest Common Divisor</a> Wikipedia page.
*
* <b>Example usage:</b>
* <pre>
* 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
* </pre>
* @author Oskar Enmalm 3/10/17
*/
public final class GCD {
Expand Down Expand Up @@ -40,20 +54,12 @@ 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);
}

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
}
}
5 changes: 5 additions & 0 deletions src/test/java/com/thealgorithms/maths/GCDTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down