zoukankan      html  css  js  c++  java
  • 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内所有35的倍数的和

     

     

    方法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
    ",sum);
    11 }
    View Code

     

    方法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
    ",ans1+ans2-ans3);
    }
    View Code

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

    版权声明:本文允许转载,转载时请注明原博客链接,谢谢~
  • 相关阅读:
    pixijs设置层级的方法
    6.Linux CPU实时监控mpstat命令详解
    5.Linux vmstat命令详解
    4.Linux iostat命令详解
    3.linux top 命令详解
    2.linux sort 命令详解
    1.Linux vim命令详解
    0.Linux命令参考博客
    洛谷 U140956 新漂亮国大选
    CF457C Elections
  • 原文地址:https://www.cnblogs.com/Dillonh/p/8490001.html
Copyright © 2011-2022 走看看