euler001题

题目: 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整除的数字加起来,所以最简单的解法就是暴力遍历:

1
print sum([x for x in range(1,1000) if x%3==0 or x%5==0])

解法二

当然,这个解法很简单,但不优雅,所以再用数学思维梳理一下刚才的题目,看看能不能总结出规律

1
2
3
4
5
6
#3的倍数相加
3+6+9+...+999=3*(1+2+3+...+333)
#5的倍数相加
5+10+15+...+995=5*(1+2+3+...+195)
#1-n的累加公式
1+2+3+...+n=(n*(n+1))/2

这样一写就简明多了,当让不要忘了在这两个数列里有3和5的公倍数被计算了两次,千万不要忘记减掉

1
2
3
4
def (n):
p = 999/n
return n*(p*(p+1))/2
print sumdivisibleby(3)+sumdivisibleby(5)-sumdivisibleby(15)

-EOF-