题目
3 或 5 的倍数
在小于 10 的自然数中,3 或 5 的倍数有 3 、 5 、 6 和 9 ,这些数之和是 23 。
求小于 1000 的自然数中所有 3 或 5 的倍数之和。
Multiples of 3 or 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.
解题方法
用集合 A 表示大于 1 小于 1000 的 3 的倍数。
显然集合 A 中的数据是首项是 3 ,公差是 3 的等差数列的前 ⌊31000⌋ 项。
用集合 B 表示大于 1 小于 1000 的 5 的倍数。
显然集合 B 中的数据是首项是 5 ,公差是 5 的等差数列的前 ⌊51000⌋ 项。
用集合 C 表示大于 1 小于 1000 的 15 的倍数。
显然集合 C 中的数据是首项是 15 ,公差是 15 的等差数列的前 ⌊151000⌋ 项,且 C=A∩B
根据容斥原理,显然
x∈A∪B∑x=a∈A∑a+b∈B∑b−c∈C∑c
参考代码
1
| print((3+999)*(1000//3)/2 + (5+995)*(1000//5)/2 - (15+990)*(1000//15)/2)
|
参考链接