Question
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.
思路
- 暴力列举所有包含3,5因子的数,进行求和
- 1000以内以3,5为因子的数的和,即考虑能被3,5各自整除的数的和,再去除能被15整除的数即可。
Python 代码
暴力列举法
1 2 3 4 5 6 7 8 9 10
|
def (n): all_sum = 0 for i in range(1, n): if i%3 == 0: all_sum += i elif i%5 == 0: all_sum += i return all_sum
sum_of_multiples1(1000)
|
233168
公式法
1 2 3 4 5 6 7 8 9 10
|
def sum_of_multiples(n): third_count = (n-1) // 3 five_count = (n-1) // 5 fifteen_count = (n-1) // 15 print(third_count, five_count, fifteen_count) all_sum = 3 * (third_count)*(1+third_count)/2 + 5 * (five_count)*(1+five_count)/2 - 15 * (fifteen_count)*(1+fifteen_count)/2 return int(all_sum)
sum_of_multiples(1000)
|
333 199 66
233168
近期评论