so i'm trying to create a fibonacci sequence and I found the following syntax which works
x <- 0
y <- 1
fib <- c()
while (x < 4000000 & y < 4000000){
x <- x y
y <- x y
fib <- c(fib, x, y)
}
However, this syntax only create the vector as long as the value of the x
and y
which is used in the calculation doesn't exceed 4,000,000. is it possible to makes the while refer to "if vector fib has less than let's say 100 element"?
thanks in advance
CodePudding user response:
Here's another way to write the code -
fib <- numeric(100)
fib[1] <- 0
fib[2] <- 1
i <- 2
while (i < 100){
i = i 1
fib[i] = fib[i-1] fib[i-2]
}
Growing vector in a loop (fib = c(fib, x, y)
) is inefficient so I have created a vector of fixed length (100) and then assigned the value to it. This also avoid creation of unnecessary temporary variables x
and y
.
CodePudding user response:
Just define another variable for using inside the while
loop and increase it by the length of the fib,
x <- 0
y <- 1
mylen <- 0 # new variable
fib <- c()
while (mylen<100){
x <- x y
y <- x y
fib = c(fib, x, y)
mylen <- length(fib)
}
CodePudding user response:
Making a very slight change to your code, use the length()
function check the length (number of elements) of fib
before each iteration of the while loop.
while(length(fib)<100){....}
This way you avoid creating a further variable to count the number of iterations, as in the other answers.
For what it's worth, this is how I would do it - a for loop is more appropriate as you have a set number of iterations
n <- 100
fib <- c(0,1)
for(i in 3:n){
fib[i] <- fib[i-2] fib[i-1]
}