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.
通常解法:
通常解法:
def SumOfAllMultiplesOf3n5-1(limit):
sum = 0
for i in range(3, limit):
if not i % 3 or not i % 5:
sum += i
return sum
这种办法效率太低,无法处理大数字!
本题实际上是求3的倍数和与5的倍数和只和减去之间重复的15的倍数和的部分!这样避免了使用大量模运算,提高效率:def SumOfAllMultiplesOf3n5-2(limit):
sum = 0
for i in range(3, limit, 3): sum += i
for i in range(5, limit, 5): sum += i
for i in range(15, limit, 15): sum -= i
return sum
使用等差数列求和公式,复杂度为O(1):
def SumOfAllMultiplesOf3n5-3(limit):
q3, r3 = divmod(limit - 1, 3)
q5, r5 = divmod(limit - 1, 5)
q15, r15 = divmod(limit - 1, 15)
return (3+limit-r3-1)*q3/2 + (5+limit-r5-1)*q5/2 - (15+limit-r15-1)*q15/2