I'm trying to implement the accept answer in this question in java:
Greatest Common Divisor from a set of more than 2 integers
But I don't know how to implement the aggregate function.
I'm trying to implement the accept answer in this question in java:
Greatest Common Divisor from a set of more than 2 integers
But I don't know how to implement the aggregate function.
There is a one-liner when using Java 8:
public class GCD {
public static void main(String[] args) {
int[] ints = { 42, 21, 14, 70 };
System.out.println(gcd(ints));
}
public static int gcd(int[] ints) {
return Arrays.stream(ints).reduce((a, b) -> gcd(a, b)).getAsInt();
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
Output is "7". The aggregate function is called a reduction.
Alternative: The lambda can also be written with a method reference.
public static int gcd(int[] ints) {
return Arrays.stream(ints).reduce(GCD::gcd).getAsInt();
}