‘’‘
注:不标题题目出处
If we list all the natural numbers below 10that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiplesis 23.
Find the sum of all the multiples of 3 or 5below 1000.
某个数以内的所有3,5的倍数的和
'''
对于这个问题,大家一般想到的会是如下解决方案:
n = 1000
res = 0
for i in xrange(n):
<span style="white-space:pre"> </span>if i % 3 == 0 or i % 5 == 0:
<span style="white-space:pre"> </span>res += i
print res
简单快捷
对于python来说,似乎还有更好的处理方案:
n = 1000
numbers = [i for i in xrange(n) if i % 3 == 0 or i % 5 == 0]
print sum(numbers)
这样处理虽然更符合python,我们是否可以让它一般化
处理成函数:
def multiples_sum(n, one=3, two=5):
<span style="white-space:pre"> </span>return sum([i for i in range(n) if i % one == 0 or i % two == 0])
print multiples_sum(1000)
def multiples_reduce(n, one=3, two=5):
<span style="white-space:pre"> </span>return reduce(lambda x,y : x+y, [i for i in range(n) if i % one == 0 or i % two == 0])
这里引用他人的一个想法,这是欧拉项目的题目,所以都可以用数学方法来解决
想法:某个数字范围内,对与3或5的倍数的和,可以理解为3的倍数和
Python表示:
def multiples_sum(n, one=3, two=5):
three = one * two
numbers = [i for i in xrange(n)]
return sum(numbers[one:n:one]) + sum(numbers[two:n:two]) - sum(numbers[three:n:three])