PE其他解题报告请参考这里,本题答案在留言首条
Multiples of 3 and 5
Problem 1
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.
题意:让你找小于1000的能被3或5整除的数的和
分析: 由于范围很小,直接可以暴力的跑,但是如果现在题目把1000, 变成
1
0
1000
10^{1000}
101000,怎么算呢,怕是不能暴力了吧,还是有点技巧的,我们可以利用容斥的思路。
答案 = {所有三的倍数的数的和} + {所有5的倍数的数的和} - {所有15的倍数的数的和}
这里用到了等差数列的前n项和
S
n
=
n
∗
a
1
+
n
(
n
−
1
)
d
2
S_n= n*a_1+ \frac{n(n-1)d}2
Sn=n∗a1+2n(n−1)d
如果这里不是3,5 了,而是更多的数,参考这里,证明的开始一点部分,或者自行百度。
c++暴力代码
#include <bits/stdc++.h>
using namespace std;
int main() {
int sum = 0;
for (int i = 0; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
cout << sum << endl;
return 0;
}
c++容斥代码
#include <bits/stdc++.h>
using namespace std;
int sum_by_x(int x) {
int cnt = 999 / x;
int sum = cnt * x + (cnt * (cnt - 1)) / 2 * x;
return sum;
}
int main() {
int sum_by_3 = sum_by_x(3);
int sum_by_5 = sum_by_x(5);
int sum_by_15 = sum_by_x(15);
cout << sum_by_3 + sum_by_5 - sum_by_15 << endl;
return 0;
}