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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With