Ewa Michalska
Ewa Michalska

Reputation: 95

Fibonacci number using Repeat loop

How could I use a repeat loop to find the biggest Fibonacci number until e.g. 1000 (so that it is less than 1000)?

I found that it is possible doing it with a while loop but how would I go around doing it with repeat?

Upvotes: 0

Views: 498

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173928

You need to test for the condition that makes you break from repeat, otherwise it will continue cycling forever:

# Set the first two numbers of the series
x <- c(0, 1)

repeat {
  # Add the last two numbers of x together and append this value to x
  x <- c(x, sum(tail(x, 2))) 

  # Check whether the last value of x is above 1000, if so chop it off and break
  if(tail(x, 1) > 1000) {
    x <- head(x, -1)
    break
  }
}

# x now contains all the Fibonacci numbers less than 1,000
x
#> [1]   0   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

Upvotes: 2

Related Questions