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

前端 未结 16 992
时光说笑
时光说笑 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:01

    int Sum(int N) {
    long long c = 0;
        N--; //because you want it less than 1000 if less than or equal delete this line
        int n = N/3,b = N/5,u = N/15;
        c+= (n*(n+1))/2 * 3;
        c+= (b*(b+1))/2 * 5;
        c-= (u*(u+1))/2 * 15;
        return c;
    }
    

提交回复
热议问题