欧拉项目(Project Euler)Problem 1

欧拉项目链接:https://projecteuler.net/archives

题目链接:https://projecteuler.net/problem=1

题目描述:Ifwe list all the natural numbers below 10 that are multiples of 3 or 5, we get3, 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内所有35的倍数的和

 

方法1:用C++就一个for即可,代码如下:

#include <cstdio>

int main(){
    int sum=0;
    for(int i=1;i<1000;i++){
        if(i%3==0 || i%5==0){
            sum+=i;
        }
    }
    printf("%d\n",sum);
}

方法2:这里只求1000内满足题意的和,但是如果数字大一点,那么用for来的话,跑得时间就太长了。那么就得换一种简单的思路,由题目可以联想到容斥定理,先将3515的所有倍数的和求出来(分别记作ans1ans2ans3),那么题目所要求的就是ans1+ans2-ans3。而求ans1,2,3直接用等差数列的求和公式即可,代码如下:

#include <cstdio>

int main(){
    int a=999/3,b=999/5,c=999/15;  //分别存有多少个3、5、15的倍数
    int ans1=(a+1)*a*3/2,ans2=(b+1)*b*5/2,ans3=(c+1)*c*15/2;
    printf("%d\n",ans1+ans2-ans3);
}

我暂时就想到这两种方法,如果看我博客的老铁有其他思路,还请在评论区告诉我,谢谢啦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值