美文网首页
和果子一起来做题-Project Euler-12-R语言版本

和果子一起来做题-Project Euler-12-R语言版本

作者: 9d760c7ce737 | 来源:发表于2018-01-28 18:22 被阅读24次
    The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
    1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
    Let us list the factors of the first seven triangle numbers:
    1: 1
    3: 1,3
    6: 1,2,3,6
    10: 1,2,5,10
    15: 1,3,5,15
    21: 1,3,7,21
    28: 1,2,4,7,14,28
    We can see that 28 is the first triangle number to have over five divisors.
    What is the value of the first triangle number to have over five hundred divisors?
    

    首先构造一个能够判断并计算因子个数的函数

    sum_factor <- function(x){
      sum = 0
      for (i in 1:x){
        if (x %% i==0)
          sum = sum +1
      }
      return(sum)
    }
    
    i =0
    repeat{
      i = i +1
      j = sum(1:i)
      if (sum_factor(j) > 500) break
    }
    

    运行半天没反应,我知道肯定出了问题!去掉函数,直接写成一下形式,满心欢喜。

    i =0
    repeat{
      i = i +1
      x = sum(1:i)
      if (sum(x%%seq(1:x)==0) > 500) break
    }
    

    还是不出来,我看到别人的Python代码,基本上是秒出。
    我想到,可能是我寻找因数的方法太缓慢,所有我又重新构造了一个函数

    sum_factor <- function(x){
      if (x==1){a=1}
      if (x==2){a=2}
      if (x==3){a=2}
      if (round(sqrt(x))==sqrt(x)){
        a=sum(x%%seq(1:round(sqrt(x)))==0)*2-1
      }else{
        a=sum(x%%seq(1:round(sqrt(x)))==0)*2
      }
      return(a)
    }
    
    i =0
    while (TRUE) {
      i = i +1
      x = sum(1:i)
      if (sum_factor(x) > 500) break
    }
    

    基本上是1秒出,76576500。

    笔记:R语言中的round,floor,ceiling函数
    round 是四舍五入
    floor是向下取整
    ceiling是向上取整
    例子如下

    > round(5.3)
    [1] 5
    > round(5.6)
    [1] 6
    > round(5.5)
    [1] 6
    > floor(5.3)
    [1] 5
    > floor(5.6)
    [1] 5
    > ceiling(5.3)
    [1] 6
    > ceiling(5.6)
    [1] 6
    

    相关文章

      网友评论

          本文标题:和果子一起来做题-Project Euler-12-R语言版本

          本文链接:https://www.haomeiwen.com/subject/ctezaxtx.html