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

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

作者: 9d760c7ce737 | 来源:发表于2018-01-28 18:21 被阅读31次

第七题:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?

找出第10001个质数。

在解决第三个问题时我们已经有了找质数的函数:

findprime <- function(x) {
  if (x %in% c(2,3,5,7)) return(TRUE)
  if (x%%2 == 0 | x==1) return(FALSE)
  xsqrt <- round(sqrt(x))
  xseq <- seq(from=3,to=xsqrt,by=2)
  if (all(x %% xseq !=0)) return(TRUE)
  else return(FALSE)
}

下面使用的是repeat循环:

i <- 1
a <- 0
repeat{
  a <- a + sum(findprime(i)) #如果是质数,a的数值就加1
  if (a==10001) break #如果到了10001就终止
  i <- i +1
}

速度也是很快
这时返回的i= 104743

相关文章

网友评论

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

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