Search code examples
javaalgorithmjava-8java-streamgreatest-common-divisor

Finding the Greatest Common Divisor using Java Stream without recursion while/for loops


Please help me out here. I need to convert the following code to one that uses Java Streams. The method used is the Euclidean Algorithm

public int gcd(int m, int n) {
    if (n == 0) {
        return m;
    } else {
        return gcd(n, m%n);
    }

I have already tried to use streams in the following way, however recursions are not allowed and I am stuck at trying to come up with a way without recursion and loops since I am still new to the declarative approach

return IntStream.of(m, n).reduce(0, (x, y) -> gcd(n, m-n));

Solution

  • Almost verbatim implementation of Euclidean algo you have as an example with stream:

    int gcd(int m, int n) {
        return Stream.iterate(new int[]{m, n}, vals -> new int[] {vals[1], vals[0] % vals[1]}).filter(v -> v[1] == 0).findFirst().get()[0];
    }
    

    It uses what's known in functional programming as accumulator concept.

    PS it would be more efficient to swap values in the array to avoid creating a new array every time but even with this new array it's much more efficient algo than the brute force one provided in another answer.