Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the sum of divisors using Java streams?

I am trying to convert this function to use Java 8 new syntax. Hopefully it will reduce the number of lines and perhaps make things clearer.

public int divisorSum(int n) {
    int sum = 0;
    for(int i = 1; i <= n; i ++) {
        if(n % i == 0) {
            sum = Integer.sum(sum, i);
        }
    }
    return sum;
}

I tried this:

IntStream.range(0, n).forEach(i -> ... )

But according to a comment on this post by Tezra apparently it is not advisable to loop using lambdas.

like image 696
GilbertS Avatar asked Dec 17 '22 13:12

GilbertS


1 Answers

Here's the Java 8 streams implementation:

public int divisorSum(int n) {
    return IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
}

Note that rangeClosed, like your example, includes n. range() excludes the second parameter (it would only include up to n-1).

like image 192
MyStackRunnethOver Avatar answered Dec 29 '22 23:12

MyStackRunnethOver