Find the sum of all the multiples of 3 or 5 below 1000

前端 未结 16 946
时光说笑
时光说笑 2020-12-10 16:41

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. I have the following code but the answer do

16条回答
  •  失恋的感觉
    2020-12-10 17:20

    Think declaratively - what you want to do, rather than how you want to do.

    In plain language, it boils down to exactly what the problem asks you to do:

    1. Find all multiples of 3 or 5 in a certain range (in this case 1 to 1000)
    2. Add them all up (aggregate sum)

    In LINQ, it looks like:

    Enumerable.Range(1, 1000)
                .Where(x => (x % 3 == 0) || (x % 5 == 0))
                .Aggregate((accumulate, next) => accumulate += next);
    

    Now, you can convert this into an iterative solution - but there is nothing wrong with using a declarative solution like above - because it is more clear and succinct.

提交回复
热议问题