如何使用Java流查找除数的和?

huangapple go评论87阅读模式
英文:

How to find the sum of divisors using Java streams?

问题

我正在尝试将这个函数转换为使用Java 8的新语法。希望能减少代码行数,或许能使代码更清晰。

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;
}

我尝试了以下内容:

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

但根据这个帖子中Tezra的评论,显然不建议使用lambda进行循环。

英文:

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 &lt;= n; i ++) {
        if(n % i == 0) {
            sum = Integer.sum(sum, i);
        }
    }
    return sum;
}

I tried this:

IntStream.range(0, n).forEach(i -&gt; ... )

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

答案1

得分: 4

这是Java 8流的实现:

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

注意,rangeClosed与你的示例一样,包括 nrange() 则排除第二个参数(它只会包括到 n-1)。

英文:

Here's the Java 8 streams implementation:

public int divisorSum(int n) {
    return IntStream.rangeClosed(1, n).filter(i -&gt; 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).

答案2

得分: 3

你可以使用IntStreamfilterIntStream::sum来实现相同的结果,这个流直接返回int,因为这个流是拆箱的:

int sum = IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
英文:

You can achieve the same result using IntStream, filter and IntStream::sum that directly returns int since this stream is unboxed:

int sum = IntStream.rangeClosed(1, n).filter(i -&gt; n % i == 0).sum();

答案3

得分: 3

你可以像这样做:

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

You can do something like this

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

答案4

得分: 1

这可能会有所帮助。

int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).reduce(0, (x, y) -> x + y);

或者

int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).sum();
英文:

This can be helpful.

int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -&gt; n % x == 0).reduce(0, (x, y) -&gt; x + y);

or

int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -&gt; n % x == 0).sum();

huangapple
  • 本文由 发表于 2020年4月8日 01:46:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61086189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定