Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

r - Finding the largest Fibonacci number less than x with repeat function

I am new to the R programming and my skill with R is at intermediate level. I have been trying to solve question related to repeat function, but cant find any solution for it. I want to find the largest Fibonacci number that is less than 5000 using repeat() loop function, but my code gives me an error. I would highly appreciate any assistance related to question and giving me the right code for the question.

fib<- c(0,1)

i<-2

repeat(fib[i]<5000){
  
  print(fib)
  
  fib<- c(fib, fib[i-1] + fib[i-2])
  
  i<- i+1
  
  if(i<5000){
    
    break
  
  }

}
question from:https://stackoverflow.com/questions/65875576/finding-the-largest-fibonacci-number-less-than-x-with-repeat-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...