3

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.

Community
  • 1
  • 1
Ogen
  • 6,499
  • 7
  • 58
  • 124

1 Answers1

9

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();
}
Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
  • Accepted answer because it does work but I was hoping there would be a j7 solution. – Ogen Jul 25 '14 at 06:18
  • The aggregation is not part of the language specification. Streams and all those operations on streams are parts of the Java 8 libraray. In previous versions you must implement them yourself or use Guava (they have also some nice features for that). Unfortunately, you don't have lambdas then. – Seelenvirtuose Jul 25 '14 at 06:46