您的位置:首页 > 其它

Multiples of 3 and 5

2015-07-09 14:56 260 查看

Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.

using System;
using System.Linq;

public static class Kata
{
public static int Solution(int value)
{
// Magic Happens
return value == 0 ? 0 : Enumerable.Range(1, value - 1).Where(x => (x % 3 == 0 || x % 5 == 0)).Aggregate(0, (sum, y) => sum + y);
}
}


其他人的解法:

如果只是简单的求和的话,可以直接使用Sum函数, Aggregate一般是在对每一项做了处理之后才使用的

using System.Linq;

public static class Kata
{
public static int Solution(int value)
{
if (value == 0)
return 0;

return Enumerable
.Range(1, value - 1)
.Where(x => x % 3 == 0
|| x % 5 == 0)
.Sum();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: