My vote's on closed form as @bdecaf suggested (because it would annoy your teacher):
vast = function(n) round(((5 + sqrt(5)) / 10) * (( 1 + sqrt(5)) / 2) ** (1:n - 1))
But you can fix the code you already have with two minor changes:
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)
}
I would still follow some of the suggestions already given--especially using different names for your vector and your function, but the truth is there are lots of different ways to accomplish your goal. For one thing, it really isn't necessary to initialize an empty vector at all in this instance, since we can use for
loops in R to expand the vector as you were already doing. You could do the following, for instance:
vast=function(n){
x = c(1,1)
for(i in 3:n) x[i] = x[i-1] + x[i-2]
return(x)
}
Of course, we all have things to learn about programming, but that's why we're here. We all got help from someone at some point and we all get better as we help others to improve as well.
UPDATE: As @Carl Witthoft points out, it is a best practice to initialize the vector to the appropriate size when that size is known in order save time and space, so another way to accomplish this task would be:
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)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…