欧拉计划第1题:Multiples of 3 or 5(容斥原理 等差数列)

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 3515 在小于 1000 1000 1000 的各自的倍数之和分别为 166833 、 99500 、 33165 166833、99500、33165 1668339950033165

通过容斥原理可知, 15 15 15 的倍数在 3 、 5 3、5 35 的倍数里面被算了两次,所以要减掉一份。

代码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.”

“欧拉计划的存在,是为了每个对数学感兴趣的人,鼓励他们,挑战他们,并最终培养他们的能力与乐趣。”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值