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

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

作者: 9d760c7ce737 | 来源:发表于2017-11-23 16:46 被阅读25次

Project Euler01
Problem 2, Even Fibonacci numbers

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

400万以内的偶数斐波那契数列求和

x[1] <- 1
x[2] <- 2
for (i in 3:1000){
  x[i]=x[i-1] +f[i-2]
  if (x[i] > 4000000){
    break
  }
}
x <- x[-i]
sum(x[x %% 2 == 0])

结果4613732
但是我并不知道x[i] > 4000000时i是多少,看了别人的答案可以使用while解决这个问题

i <- 2
x <- 1:2
while (x[i] < 4e6) {
  x[i+1] <- x[i-1] + x[i]
  i <- i + 1
}
x <- x[-i]
sum(x[x %% 2 == 0])

看了一下r-bloggers上别人的答案
发现还可以用repeat这个命令

fibonacci <- numeric()
fibonacci[1] <- 1
fibonacci[2] <- 2
i <- 3
repeat {
  fibonacci[i] <- fibonacci[i-1] + fibonacci[i-2]
  if (fibonacci[i] > 4e6) break
  i <- i + 1
}
# calculate the sum
fibonacci <- fibonacci[-length(fibonacci)]  # remove the last term
flag <- fibonacci %% 2 == 0  # find the indexes of even numbers
result <- sum(fibonacci[flag])
cat("The result is:", result, "\n")

现在有两个问题
1.repeat和while有什么区别?
2.R语言中的循环有多少种?
for,while,repeat,向量化操作,apply,自己写的函数也算。
这里有一份来自Datacamp的Tutorials十分值得阅读,价值250美元,很长很全面,但是很好懂
A Tutorial on Loops in R - Usage and Alternatives

相关文章

网友评论

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

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