0

I was trying to save all items in Fibonacci sequence till a given number n. For example, if the function is fib, my expected out would be

  • 1 1 2 for fib(3)
  • 1 1 2 3 5 for fib(5)
  • 1 1 2 3 5 8 13 21 for fib(8)

so on and so forth.

My code is

fib <- function(n) {
  if (n<= 2) {
    return(1)
  } else {
    return(f(n-1)+f(n-2))
  }
}

but it only gives a single value for the n-th elements in the Fibonacci sequence.

Any clue to save the elements from 1 to n as the output of fib(n)? Thank you!

2 Answers2

1

I think you have a couple of ways to make it:

  • Approach 1: Redefine fib in a recursive manner
fib <- function(n) {
  if (n<=2) return(rep(1,n))
  c(u <- Recall(n-1),sum(tail(u,2)))
}

such that

> fib(10)
 [1]  1  1  2  3  5  8 13 21 34 55

> fib(20)
 [1]    1    1    2    3    5    8   13   21   34   55   89
[12]  144  233  377  610  987 1597 2584 4181 6765
  • Approach 2: Use your fib but with sapply
fib1 <- function(n) sapply(seq(n),fib)

such that

> fib1(10)
 [1]  1  1  2  3  5  8 13 21 34 55

> fib1(20)
 [1]    1    1    2    3    5    8   13   21   34   55   89
[12]  144  233  377  610  987 1597 2584 4181 6765
  • Approach 3: Use for loop (I think this would be the most efficient one among three approaches)
fib2 <- function(n) {
  r <- rep(1,n)
  if (n>=3) {
    for (k in 3:n) {
      r[k] <- sum(r[k-(1:2)])
    }
  }
  r
}

such that

> fib2(10)
 [1]  1  1  2  3  5  8 13 21 34 55

> fib2(20)
 [1]    1    1    2    3    5    8   13   21   34   55   89
[12]  144  233  377  610  987 1597 2584 4181 6765
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
0

If you want to do this as a recursion, you need to append each item to the front of the list (depending on the order you want the elements in.

You could also do this as a for loop and then the indexing would be more straightforward. You could use the function you already wrote, but it would be inefficient. It would be faster to access the i-1 and i-2 elements of your array to calculate the ith element.

Right now you're not storing the preceding elements anywhere.

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134