fixed bug in method gcd(int, int)

This commit is contained in:
Christian Bender 2018-07-25 17:07:34 +02:00
parent c86ba856a8
commit 161791d4a5

View File

@ -6,13 +6,19 @@ public class GCD{
public static int gcd(int num1, int num2) {
int gcdValue = num1 % num2;
while (gcdValue != 0) {
num2 = gcdValue;
gcdValue = num2 % gcdValue;
}
if (num1 == 0)
return num2;
while (num2 != 0) {
if (num1 > num2)
num1 -= num2;
else
num2 -= num1;
}
return num1;
}
public static int gcd(int[] number) {
int result = number[0];
for (int i = 1; i < number.length; i++)
@ -24,7 +30,9 @@ public class GCD{
public static void main(String[] args) {
int[] myIntArray = { 4, 16, 32 };
// call gcd function (input array)
System.out.println(gcd(myIntArray));
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
}
}