Create m Fibonacci numbers

fibonacci <- function(m) {
m <- numeric(m)
t1 <- 0
t2 <- 1
for (i in 1:m) {
val <- t1 + t2
print(val)
}
}

If i now enter fibonacci(10), it says it only uses the first element, the rest remain unused.

you immediately take the number m and make an object m which is also numeric, but full of zero's of length the number m that was first given. i.e 0 0 0 0
the error therefore refers to your instruction to take i from in 1:m as defining some integer sequence starting from 1 and ending at ... 0 0 0 0 is only possible if one ignores every subsequent 0 to the first .

amusingly I asked the Artificial Intelligence chatbot over at ChatGPT (openai.com)

function to generate fibonacci sequence from 1 to n , in R ?
and it answered with the following

# define a function that generates the Fibonacci sequence

fibonacci <- function(n) {
  # define the starting values
  a <- 0
  b <- 1

  # check if the number of terms is 0 or 1
  if (n == 0) {
    return(a)
  } else if (n == 1) {
    return(c(a, b))
  } else {
    # generate the Fibonacci sequence
    seq <- c(a, b)
    for (i in 2:n) {
      c <- a + b
      seq <- c(seq, c)
      a <- b
      b <- c
    }
    return(seq)
  }
}

# test the function with different values of n
print(fibonacci(0)) # 0
print(fibonacci(1)) # 0, 1
print(fibonacci(2)) # 0, 1, 1
print(fibonacci(3)) # 0, 1, 1, 2
print(fibonacci(4)) # 0, 1, 1, 2, 3

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.