'''
Created on 2014年8月20日
problem1 : Multiples 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.
@author: wxp2971
'''
# 最直接的方式,当数值比较大的时候,计算时间比较长,考虑递推公式
def calcSum1(targetNum, numA, numB):
sum1 = 0
for i in range(targetNum):
if (i%numA == 0) or (i%numB == 0):
sum1 += i
return sum1
# 递推公式方法,等差数列求和
def SumDivisibleBy(x, targetNum):
targetNum -= 1
retSum =(x + int(targetNum/x)*x) * int(targetNum/x)/2 # 求和公式 sum = (a_0 + a_n)*n/2
return int(retSum)
def calcSum2(targetNum, numA, numB):
sum = SumDivisibleBy(numA,targetNum) + SumDivisibleBy(numB,targetNum) - SumDivisibleBy(numA*numB,targetNum)
return sum
# 测试运行时间
import time
for num in range(10000,100000,10000):
starttime1 = time.clock()
targetNum = num; numA= 3; numB = 5
sum1 = calcSum1(targetNum, numA, numB)
endtime1 = time.clock()
print (sum1,endtime1-starttime1)
starttime1 = time.clock()
targetNum = num; numA= 3; numB = 5
sum2 = calcSum2(targetNum, numA, numB)
endtime1 = time.clock()
print (sum2,endtime1-starttime1)
'''Created on 2014年8月20日problem1 : Multiples 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