简体   繁体   English

斐波那契数列是否有 R function ?

[英]Is there a R function for Fibonacci sequence?

Function in R, again, call it "f1", that takes n as an input, so f1<-function(n) {} and computes a Fibonacci sequence up to the value n, but where the sequence sums the last three rather than only last 2 numbers. R 中的 Function 再次将其称为“f1”,它将 n 作为输入,因此 f1<-function(n) {} 并计算一个斐波那契数列,直到值 n,但该数列将最后三个相加而不是只有最后2个数字。 So the sequence is 1 1 1 3 5 9 17...所以序列是 1 1 1 3 5 9 17...

Try this code试试这个代码

f <- function(n) {
  v <- numeric(n)
  for (i in seq(n)) {
    if (i <= 3) {
      v[i] <- 1
    } else {
      v[i] <- sum(v[i - (1:3)])
    }
  }
  v
}

and you will see你会看到

> f(10)
 [1]   1   1   1   3   5   9  17  31  57 105

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM