The "easy" solution to compute the Fibonacci numbers is fibo <- function(n,a=1,b=1){ if (n == 1) return(a) if (n == 2) return(b) return(fibo(n-1,b,a+b)) }
It avoids double recursion. It is, however, not as resource efficient as a loop since R does not do tail recursion elimination. On Apr 20, 2011, at 11:42 AM, Georgina Imberger wrote: > Hi! > > I am trying to work out the code to get a Fibonacci sequence, using the > while() loop and only one variable. And I can't figure it out. > > Fibonacci<-c(1,1) > while (max(Fibonacci)<500){ > Fibonacci<-c(Fibonacci, (max(Fibonacci) + ?(Fibanacci))) > } > > > How can I tell R to take the value one before the max value? (Without > defining another variable) > > (Probably super easy... I am a beginner...) > > Thanks, > Georgie > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.