mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
Remove main function from GCD class (#5828)
This commit is contained in:
@ -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 {
|
||||
@ -40,7 +54,7 @@ public final class GCD {
|
||||
* @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 final class GCD {
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
@ -40,6 +40,11 @@ public class GCDTest {
|
||||
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);
|
||||
|
Reference in New Issue
Block a user