
题目: 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 |
#3的倍数相加 |
这样一写就简明多了,当让不要忘了在这两个数列里有3和5的公倍数被计算了两次,千万不要忘记减掉
1 |
def (n): |
-EOF-




近期评论