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.
Q: Find the sum of all the multiples of 3 or 5 below 1000.
def problem1(a, b, bl):''' 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 a or b below "bl". '''
result =0for i inrange(1, bl):
temp = a * i #temp is multiples of aif temp >= bl:break
result += temp
for i inrange(1, bl):
temp = b * i #temp is multiples of bif temp >= bl:breakif temp %3==0:#temp is multiples of b but no a, so temp is not multiples of a*bcontinue
result += temp
return result
def problem1(a, b, bl):''' 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 a or b below "bl". '''
result =0
c =(bl -1)// a #have c number multiples of a
d =(bl -1)// b #have d number multiples of b
e =(bl -1)//(a * b)#have e number multiples of a * bfor i inrange(1, c +1):
result += a * i #a * i is multiples of afor i inrange(1, d +1):
result += b * i #b * i is multiples of bfor i inrange(1, e +1):
result -= a * b * i
return result
0 nhận xét:
Đăng nhận xét