Projext Euler Problem 1:Multiples of 3 and 5【暴力】【容斥】

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=na1+2n(n1)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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值