Multiples of 3 and 5
欧拉项目链接: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内所有3或5的倍数的和
方法1:用C++就一个for即可,代码如下:

1 #include <cstdio> 2 3 int main(){ 4 int sum=0; 5 for(int i=1;i<1000;i++){ 6 if(i%3==0 || i%5==0){ 7 sum+=i; 8 } 9 } 10 printf("%d\n",sum); 11 }
方法2:这里只求1000内满足题意的和,但是如果数字大一点,那么用for来的话,跑得时间就太长了。那么就得换一种简单的思路,由题目可以联想到容斥定理,先将3、5、15的所有倍数的和求出来(分别记作ans1,ans2,ans3),那么题目所要求的就是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); }
我暂时就想到这两种方法,如果看我博客的老铁有其他思路,还请在评论区告诉我,谢谢啦~
版权声明:本文允许转载,转载时请注明原博客链接,谢谢~