Problem 1:Multiples of 3 3 3 or 5 5 5
标签:倍数、容斥原理、等差数列
原文:If we list all the natural numbers below 10 10 10 that are multiples of 3 3 3 or 5 5 5, we get 3 3 3, 5 5 5, 6 6 6 and 9 9 9. The sum of these multiples is 23 23 23.
Find the sum of all the multiples of 3 3 3 or 5 5 5 below 1000 1000 1000.
翻译:在小于 10 10 10 的自然数中, 3 3 3 或 5 5 5 的倍数有 3 3 3、 5 5 5、 6 6 6和 9 9 9,这些数之和是 23 23 23。
求小于 1000 1000 1000 的自然数中所有 3 3 3 或 5 5 5 的倍数之和。
题解1:循环枚举一下。
代码1:
#include <bits/stdc++.h>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
cout << sum << endl;
return 0;
}
题解2:小于 1000 1000 1000 的 3 3 3 的倍数有 999 / 3 = 333 999/3=333 999/3=333 个,小于 1000 1000 1000 的 5 5 5 的倍数有 999 / 5 = 199 999/5=199 999/5=199 个,同时是 3 3 3 和 5 5 5 的倍数有 1000 / 15 = 66 1000/15=66 1000/15=66 个。
通过等差数列求和公式,我们可以求得 3 、 5 、 15 3、5、15 3、5、15 在小于 1000 1000 1000 的各自的倍数之和分别为 166833 、 99500 、 33165 166833、99500、33165 166833、99500、33165。
通过容斥原理可知, 15 15 15 的倍数在 3 、 5 3、5 3、5 的倍数里面被算了两次,所以要减掉一份。
代码2:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n3 = 999 / 3;
int n5 = 999 / 5;
int n15 = 999 / 15;
int S3 = (1 + n3) * 3 * n3 / 2;
int S5 = (1 + n5) * 5 * n5 / 2;
int S15 = (1 + n15) * 15 * n15 / 2;
cout << S3 + S5 - S15;
return 0;
}
// 等差数列求和:Sn = (1 + n) * d * n / 2
“Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.”
“欧拉计划的存在,是为了每个对数学感兴趣的人,鼓励他们,挑战他们,并最终培养他们的能力与乐趣。”