[Project Euler] 1. Mutiples 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.

 

解题思路:

可以用暴力破解法:对小于1000的数字每个进行检查:是否可以整除3或5

也可以用纯数学算法:

首先计算3 和 5的倍数的个数:

999/3 = 333

999/5 = 199

(注意这里是999作为被除数是因为要小于1000的数字)

3的倍数和5的倍数列出来其实是一个等差数列,我们可以用等差数列求和的方法:

Sum(3) = (3 + 999) * 333 / 2 = 166833

Sum(5) = (5 + 995) * 199 / 2 = 99500

此时3和5的数列中有重合项:就是15的倍数,所以我们要减去它的和

Sum(15) = (15 + 990) * 66 / 2 = 33165

最后求的的和为:166833 + 99500 - 33165 = 233168

posted @ 2018-07-10 01:23  妖域大都督  阅读(187)  评论(0编辑  收藏  举报