|
1 | 1 | package com.thealgorithms.maths; |
2 | 2 |
|
3 | 3 | /** |
4 | | - * This is Euclid's algorithm, used to find the greatest common |
5 | | - * denominator Override function name gcd |
| 4 | + * This class provides methods to compute the Greatest Common Divisor (GCD) of two or more integers. |
6 | 5 | * |
| 6 | + * 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. |
| 7 | + * |
| 8 | + * 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. |
| 9 | + * |
| 10 | + * For more information, refer to the |
| 11 | + * <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">Greatest Common Divisor</a> Wikipedia page. |
| 12 | + * |
| 13 | + * <b>Example usage:</b> |
| 14 | + * <pre> |
| 15 | + * int result1 = GCD.gcd(48, 18); |
| 16 | + * System.out.println("GCD of 48 and 18: " + result1); // Output: 6 |
| 17 | + * |
| 18 | + * int result2 = GCD.gcd(48, 18, 30); |
| 19 | + * System.out.println("GCD of 48, 18, and 30: " + result2); // Output: 6 |
| 20 | + * </pre> |
7 | 21 | * @author Oskar Enmalm 3/10/17 |
8 | 22 | */ |
9 | 23 | public final class GCD { |
@@ -40,20 +54,12 @@ public static int gcd(int num1, int num2) { |
40 | 54 | * @param numbers the input array |
41 | 55 | * @return gcd of all of the numbers in the input array |
42 | 56 | */ |
43 | | - public static int gcd(int[] numbers) { |
| 57 | + public static int gcd(int... numbers) { |
44 | 58 | int result = 0; |
45 | 59 | for (final var number : numbers) { |
46 | 60 | result = gcd(result, number); |
47 | 61 | } |
48 | 62 |
|
49 | 63 | return result; |
50 | 64 | } |
51 | | - |
52 | | - public static void main(String[] args) { |
53 | | - int[] myIntArray = {4, 16, 32}; |
54 | | - |
55 | | - // call gcd function (input array) |
56 | | - System.out.println(gcd(myIntArray)); // => 4 |
57 | | - System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 |
58 | | - } |
59 | 65 | } |
0 commit comments