Question about modifying a function

Hi everyone,

I was told to write a code for the fibonacci number and then find the dividend of the consecutive numbers to eventually find the golden ratio.
My code is:

fibonacci <- function(n)
    {
    if(n==1)
        x<- 1
    if(n==2)
        x<- c(1,1)
    if(n>2)
        {
        x<- fibonacci(2)
        for(i in 3:n)
            x[i] <- x[i-1]+x[i-2]
        y <- x[i-1]
        z <- x[i-2]
            x[i] <- y/z
        }

    return(x)
    
}

When I do fibonacci (10), it gives me:
(1, 1, 2, 3, 5, 8, 13, 21, 34, 1.61904761904762)

I do not understand why it only gives me the dividend of the 9th and 10th number. Could someone explain to me why?
Thank you for your time in advance.

Hi, and welcome to community.rstudio.com! It sounds like this might be a homework question. If it is, please see our homework policy.

To give you a gentle nudge in the right direction, what happens if you run fibonacci(3)? For n=3, I would expect the sequence 1 1 2, but I get 1 1 1. Similarly, fibonacci(4) returns 1 1 2 2, not the expected 1 1 2 3. Do you see a pattern? You should start by re-thinking the line of code that deals with y/z. Perhaps instead of overwriting x[i] the division should be handled separately.

I hope this is helpful!

2 Likes

Thank you your reply.
Also, I am sorry, I did not know about the homework policy.

I know the y/z is the only messed up part, but I will try to figure it out by myself.
Thank you again!

2 Likes