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

前端 未结 16 983
时光说笑
时光说笑 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: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);
        }
    

提交回复
热议问题