JavaAlgorithms/Others/GCD.java

28 lines
616 B
Java
Raw Normal View History

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
public class GCD{
2017-10-28 03:43:04 +08:00
public static int gcd(int a, int b) {
2017-10-03 16:02:42 +08:00
int r = a % b;
while (r != 0) {
b = r;
r = b % r;
}
return b;
}
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++)
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};
System.out.println(gcd(myIntArray));
}
2017-10-28 02:19:55 +08:00
}