|
2 | 2 | //This is Euclid's algorithm which is used to find the greatest common denominator
|
3 | 3 | //Overide function name gcd
|
4 | 4 |
|
5 |
| -public class GCD{ |
6 |
| - |
7 |
| - public static int gcd(int num1, int num2) { |
8 |
| - |
9 |
| - int gcdValue = num1 % num2; |
10 |
| - while (gcdValue != 0) { |
11 |
| - num2 = gcdValue; |
12 |
| - gcdValue = num2 % gcdValue; |
| 5 | +public class GCD { |
| 6 | + |
| 7 | + public static int gcd(int num1, int num2) { |
| 8 | + |
| 9 | + if (num1 == 0) |
| 10 | + return num2; |
| 11 | + |
| 12 | + while (num2 != 0) { |
| 13 | + if (num1 > num2) |
| 14 | + num1 -= num2; |
| 15 | + else |
| 16 | + num2 -= num1; |
13 | 17 | }
|
14 |
| - return num2; |
| 18 | + |
| 19 | + return num1; |
15 | 20 | }
|
16 |
| - public static int gcd(int[] number) { |
17 |
| - int result = number[0]; |
18 |
| - for(int i = 1; i < number.length; i++) |
19 |
| - //call gcd function (input two value) |
20 |
| - result = gcd(result, number[i]); |
21 |
| - |
22 |
| - return result; |
23 |
| - } |
24 |
| - |
25 |
| - public static void main(String[] args) { |
26 |
| - int[] myIntArray = {4,16,32}; |
27 |
| - //call gcd function (input array) |
28 |
| - System.out.println(gcd(myIntArray)); |
| 21 | + |
| 22 | + public static int gcd(int[] number) { |
| 23 | + int result = number[0]; |
| 24 | + for (int i = 1; i < number.length; i++) |
| 25 | + // call gcd function (input two value) |
| 26 | + result = gcd(result, number[i]); |
| 27 | + |
| 28 | + return result; |
| 29 | + } |
| 30 | + |
| 31 | + public static void main(String[] args) { |
| 32 | + int[] myIntArray = { 4, 16, 32 }; |
| 33 | + |
| 34 | + // call gcd function (input array) |
| 35 | + System.out.println(gcd(myIntArray)); // => 4 |
| 36 | + System.out.printf("gcd(40,24)=%d gcd(24,40)=%d\n", gcd(40, 24), gcd(24, 40)); // => 8 |
29 | 37 | }
|
30 | 38 | }
|
0 commit comments