zoukankan      html  css  js  c++  java
  • R语言学习——欧拉计划(1)Multiples of 3 and 5

    【题目一】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.

    【翻译】10以下的自然数中,属于3和5的倍数的有3,5,6和9,它们之和是23.

    找出1000以下的自然数中,属于3和5的倍数的数字之和。

    【思路一】直接一个for循环,遍历[3,1000),找出3和5的倍数,累加即可。

    【代码一】

    f<-function(){
      s<-0
      for (n in 1:1000-1)
      {
        if(n%%3==0 || n%%5==0)
        {
          print(n)
          s<-s+n
        }
      }
      print(s)
    }

    【思路二】我们容易知道1000中3的倍数可以表示为3*n,其中n属于[1,1000/3)。进而1000中3的倍数的和为3*n*(n+1)/2,据此可以得到1000中5的倍数的和,之后还需要减去1000中3和5的公倍数15的和。据此思路,编码如下:

    【代码二】

    void test1()
    {
        int n1 = 999 / 3;
        int n2 = 999 / 5;
        int n3 = 999 / 15;
        int sum =(n1 + 1)*n1 / 2 * 3 + (n2 + 1)*n2 / 2 * 5 - (n3 + 1)*n3 / 2 * 15;
        cout << sum << endl;
    }

    【答案】运行程序后,最终结果为 233168。

  • 相关阅读:
    spring-mvc-继续学习
    springMVC学习
    spring-jdbc及事务
    Spring-MVC配置思路
    spring入门-注解的使用
    spring入门
    Spring MVC——数据校验(分组校验)
    Spring MVC——数据校验(数据回显)
    Spring MVC——数据检验步骤
    Spring MVC——参数装填方式
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/13270880.html
Copyright © 2011-2022 走看看