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

前端 未结 16 938
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2020-12-10 17:21

    Just as an improvement you might want to avoid the loop altogether :

    multiples of 3 below 1000 form an AP : 3k where k in [1, 333]
    multiples of 5 below 1000 form an AP : 5k where k in [1, 199]
    

    If we avoid multiples of both 3 and 5 : 15k where k in [1, 66]

    So the answer is : 333*(3+999)/2 + 199(5+995)/2 - 66*(15+990)/2 = 233168

    Why you might want to do this is left to you to figure out.

    0 讨论(0)
  • 2020-12-10 17:22

    Here's a python one-liner that gives the correct answer (233168):

    reduce( lambda x,y: x+y, [ x for x in range(1000) if x/3.0 == int( x/3.0 ) or x/5.0 == int( x/5.0 ) ] )
    
    0 讨论(0)
  • 2020-12-10 17:25

    I attempt the Project Euler #1: Multiples of 3 and 5. And got 60 points for that.

    private static long euler1(long N) {
            long i, sum = 0;
            for (i = 3; i < N; i++) {
                if (i % 3 == 0 || i % 5 == 0) {
                sum += i;
                }
            }
            return sum;
        }
    

    I use Java for it and you can use this logic for C. I worked hard and find an optimal solution.

    private static void euler1(long n) {
            long a = 0, b = 0, d = 0;
    
            a = (n - 1) / 3;
            b = (n - 1) / 5;
            d = (n - 1) / 15;
    
            long sum3 = 3 * a * (a + 1) / 2;
            long sum5 = 5 * b * (b + 1) / 2;
            long sum15 = 15 * d * (d + 1) / 2;
            long c = sum3 + sum5 - sum15;
            System.out.println(c);
        }
    
    0 讨论(0)
提交回复
热议问题