Jayden Rice
Jayden Rice

Reputation: 301

Fibonacci sequence less than 1000 in R

I'm trying to print the Fibonacci Sequence less than 1000 using while loop in R.

So far,

fib <- c(1,1)
counter <-3
while (fib[counter-1]<1000){
  fib[counter]<- fib[counter-2]+fib[counter-1]
  counter = counter+1
}
fib

I have this code. Only the first two numbers are given: 1,1. This is printing:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

How do I fix my code to print only less than 1000?

Upvotes: 2

Views: 1092

Answers (3)

Allan Cameron
Allan Cameron

Reputation: 173928

You could change the while condition to sum the last 2 answers instead of just the last one:

fib <- c(1,1)
counter <-3
while (sum(fib[counter - 1:2]) < 1000){
    fib[counter]<- fib[counter-2]+fib[counter-1]
    counter = counter+1
}
fib
#>  [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

Or just get rid of counter completely:

fib <- c(1,1) 
while (sum(fib[length(fib) - 0:1]) < 1000) fib <- c(fib, sum(fib[length(fib) - 0:1]))
fib
#>  [1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

Upvotes: 1

Adam Jijo
Adam Jijo

Reputation: 92

Instead of checking the value of the last element wrt 1000, for the expected output you should be checking the sum of the last two elements as so.

fib <- c(1,1)
counter <-3
while (fib[counter-2]+fib[counter - 1]<1000){
  fib[counter]<- fib[counter-2]+fib[counter-1]
  counter = counter+1
}
fib

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 389055

The issue with your approach is when the condition (fib[counter-1]<1000) in while loop is FALSE you have already added the number in fib which is greater than 1000.

You could return fib[-length(fib)] to remove the last number or check the number before inserting the number in fib.

fib <- c(1,1)
counter <-3

while (TRUE){
  temp <- fib[counter-2] + fib[counter-1]
  if(temp < 1000) 
    fib[counter] <- temp
  else
    break
  counter = counter+1
}
fib
#[1]   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

Upvotes: 1

Related Questions