Problem 1 : Multiples of 3 and 5

Problem 1


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.

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


3的倍數和5的倍數

如果我們列出10以內所有3或5的倍數,我們將得到3、5、6和9,這些數的和是23。

求1000以內所有3或5的倍數的和。


題目解答

    樸素解法:暴力枚舉(需要考慮既能被3整除又能被5整除的數字只需要加一次,利用容斥原理可以解決這個問題)

    優化算法:

        我們我們通過圖片可以觀察出 3和5所有重疊的數字都是是3和5的最小公倍數的倍數,也就是15的倍數,所以我們只需要將3的倍數和與5的倍數和相加並減去15的倍數和即可。

           

    在這裏我們完全不必暴力枚舉,利用等差數列求和公式即可解決這個問題:

    等差數列求和公式推導:

                      

                    

                    

                      

    我們可以通過數學歸納法再次進行證明,這裏就不多介紹了。

題目代碼

#include <stdio.h>
#include <inttypes.h>
int32_t main() {
    int32_t sum_3 = (999 / 3) * (3 + (999/3) *3) / 2;
    int32_t sum_5 = (999 / 5) * (5 + (999/5) *5) / 2;
    int32_t sum_15 = (999 / 15) * (15 + (999 / 15) * 15) / 2;
    printf("%" PRId32 "\n",sum_3 + sum_5 - sum_15);
    return 0;
}

        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章