If we use while()
instead of repeat()
we can code a loop that will create Fibonacci numbers until the value of the most recently created number in the series is greater than 5,000.
First we'll create a function to calculate Fibonacci numbers.
fib <- function(x){
# check that x is an integer
if(!is.numeric(x)) stop("x must be an integer")
if(!(abs(x - round(x)) < .Machine$double.eps^0.5)) stop("x must be an integer")
if(x >= 2) return(fib(x-1) + fib(x-2))
if(x == 1) return(1)
if(x == 0) return(0)
if(x < 0) return(NaN)
}
Next, we'll write a while()
loop to calculate Fibonacci numbers until the most recently created one is above 5,000. We store the numbers in a vector and code the while()
loop to compare against the element at the end of the vector.
# initialize vector for Fibonacci sequence
fibSequence <- c(0,1)
# use while loop to calculate fibonacci numbers until one is greater than
# 5000
while(fibSequence[length(fibSequence)] <= 5000){
fibSequence <- c(fibSequence,fib(length(fibSequence)))
}
At this point the vector fibSequence
includes 1 value greater than 5,000. To produce a result vector that only has Fibonacci numbers less than 5,000, we trim the last number from the vector.
# trim last number
fibSequence <- fibSequence[-length(fibSequence)]
fibSequence
...and the output:
> fibSequence
[1] 0 1 1 2 3 5 8 13 21 34 55 89 144 233
[15] 377 610 987 1597 2584 4181
>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…