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.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the >number passed in. Additionally, if the number is negative, return 0 (for languages that >do have them).
Note: If the number is a multiple of both 3 and 5, only count it once.
題目理解:給定一個數字number,將所有小於此數字的自然數中,含有3或5倍數的數字相加返還該總和。同時為3或5倍數時只計算一次,若number為負值則返還0。
def solution(number):
x = 3
y = 5
lst =[]
#找出所有小於number的3的倍數,並加入lst中
while x < number :
lst.append(x)
x += 3
#找出所有小於number的5的倍數,並加入lst中
while y < number:
lst.append(y)
y += 5
#3&5的公倍數因為被計算到兩次因此在lst中重複出現,使用set()來去除重複元素
return sum(set(lst))