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

文章讲述了如何利用等差数列和容斥原理求解Euler问题,即计算小于1000的所有3和5的倍数之和。给出了两种解题方法:直接循环枚举和利用数列求和公式结合容斥原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 1:Multiples of 333 or 555

标签:倍数、容斥原理、等差数列

原文:If we list all the natural numbers below 101010 that are multiples of 333 or 555, we get 333, 555, 666 and 999. The sum of these multiples is 232323.

Find the sum of all the multiples of 333 or 555 below 100010001000.

翻译:在小于 101010 的自然数中,333555 的倍数有 333555666999,这些数之和是 232323

求小于 100010001000 的自然数中所有 333555 的倍数之和。

题解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:小于 100010001000333 的倍数有 999/3=333999/3=333999/3=333 个,小于 100010001000555 的倍数有 999/5=199999/5=199999/5=199 个,同时是 333555 的倍数有 1000/15=661000/15=661000/15=66 个。

通过等差数列求和公式,我们可以求得 3、5、153、5、153515 在小于 100010001000 的各自的倍数之和分别为166833、99500、33165166833、99500、331651668339950033165

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

代码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、付费专栏及课程。

余额充值