2017-10-03 16:02:42 +08:00
|
|
|
//Oskar Enmalm 3/10/17
|
|
|
|
//This is Euclid's algorithm which is used to find the greatest common denominator
|
2017-10-28 04:39:09 +08:00
|
|
|
//Overide function name gcd
|
2017-10-03 16:02:42 +08:00
|
|
|
|
|
|
|
public class GCD{
|
|
|
|
|
2017-10-28 04:39:09 +08:00
|
|
|
public static int gcd(int num1, int num2) {
|
|
|
|
|
|
|
|
int gcdValue = num1 % num2;
|
|
|
|
while (gcdValue != 0) {
|
|
|
|
num2 = gcdValue;
|
|
|
|
gcdValue = num2 % gcdValue;
|
2017-10-03 16:02:42 +08:00
|
|
|
}
|
2017-10-28 04:39:09 +08:00
|
|
|
return num2;
|
2017-10-03 16:02:42 +08:00
|
|
|
}
|
2017-10-28 03:43:04 +08:00
|
|
|
public static int gcd(int[] number) {
|
|
|
|
int result = number[0];
|
|
|
|
for(int i = 1; i < number.length; i++)
|
2017-10-28 04:39:09 +08:00
|
|
|
//call gcd function (input two value)
|
2017-10-28 03:43:04 +08:00
|
|
|
result = gcd(result, number[i]);
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
2017-10-28 02:19:55 +08:00
|
|
|
|
2017-10-28 03:43:04 +08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
int[] myIntArray = {4,16,32};
|
2017-10-28 04:39:09 +08:00
|
|
|
//call gcd function (input array)
|
2017-10-28 03:43:04 +08:00
|
|
|
System.out.println(gcd(myIntArray));
|
|
|
|
}
|
2017-10-28 02:19:55 +08:00
|
|
|
}
|