Skip to content

Commit 161791d

Browse files
author
Christian Bender
committed
fixed bug in method gcd(int, int)
1 parent c86ba85 commit 161791d

File tree

1 file changed

+30
-22
lines changed

1 file changed

+30
-22
lines changed

Others/GCD.java

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,37 @@
22
//This is Euclid's algorithm which is used to find the greatest common denominator
33
//Overide function name gcd
44

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;
1317
}
14-
return num2;
18+
19+
return num1;
1520
}
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
2937
}
3038
}

0 commit comments

Comments
 (0)