Fibonacci Function

We are given a task that we simply cannot understand:

Write a function R that will generate a vector containing the first n members of the Fibonacci sequence. The steps in this are as follows: (a) Create a vector to save the result. (b) Initialize the first two elements. (c) Run a loop from i, starting from 3 to n, filling in the ith element

Work so far:

vast=function(n){
 vast=vector()
 vast[1]=1
 vast[2]=1
 for(i in 3){vast[i]=vast[i-1]+vast[i-2]}
 }

We all end up with an error: an object of type “closure” is not a subset

How should we generate the desired function?

+4
source share
1 answer

My voting is in a closed form, as suggested by @bdecaf (because it would annoy your teacher):

vast = function(n) round(((5 + sqrt(5)) / 10) * (( 1 + sqrt(5)) / 2) ** (1:n - 1))

, , :

vast=function(n){
 vast=vector()
 vast[1]=1
 vast[2]=1
 for(i in 3:n){vast[i]=vast[i-1]+vast[i-2]}
 return(vast)
 }

- , , , , . -, , for R, , . , :

vast=function(n){
  x = c(1,1)
  for(i in 3:n) x[i] = x[i-1] + x[i-2]
  return(x)
}

, , , . - -, , .

: @Carl Witthoft, , , , :

vast=function(n) {
  x = numeric(n)
  x[1:2] = c(1,1)
  for(i in 3:n) x[i] = x[i-1] + x[i-2]
  return(x)
}
+5

Source: https://habr.com/ru/post/1533299/


All Articles