While loop for returning vector of Fibonacci numbers

I'd like to create a function fun(x) that returns a vector of Fibonacci numbers that are smaller or equal to x (assuming x is also a Fibonacci number). I've defined x as 21 so I would like to get back a vector containing numbers 1, 1, 2, 3, 5, 8, 13, 21. I've managed to write a code that looks like this:

> storage <- c()
> x <- 21
> storage[1] <- 1
> storage[2] <- 1
> fun <- function(x){
+ while(storage[2] <= x){
+ storage<-c(storage, storage[2])
+ temp <- storage[1] + storage[2]
+ storage[1] <- storage[2]
+ storage[2] <- temp
+ }
+ }

So I formed an empty vector and defined its first two values. Then, using while loop I tried to define the new vector and new values for storage[1] and [2] with a help of temporary (temp) variable. But the problem is that this code only gives me back a vector (1,1). What would be the easiest way to fix this? Thank you for your help!

Advanced R is a great free book, for taking your R to the next level.

Fibonnaci is used as an example of a function that can benefit from memoisation, even ignoring that though, the implementation is very elegant.

fib <- function(n) {
  if (n < 2) return(1)
  fib(n - 2) + fib(n - 1)

I see though that this doesn't directly answer your question as you asked for a vector and not simply the number. I'll get back to this when I have some time.

1 Like

 fib <- function(x){
   storage <- c()
   storage[[1]] <- 1
   storage[[2]] <- 1
   while(tail(storage,1) < x){
     next_val <- sum(tail(storage,2) )
      storage <- c(storage,next_val)
result <- fib(21)

[1]  1  1  2  3  5  8 13 21 

edit note, i dropped the equal sign in the while loop condition so on checking and getting the tail value equal to the desired x the while loop wont run (before doing this it would have calculated the next value after 21

Thank you so much! This was really helpful.

you're welcome, head and tail are super useful functions. I often use them to peek at top and bottom rows of unfamiliar datasets.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.