0

I want to write a program that prints me only the first 10 Fibonacci numbers that > 1000.

I tried using head, n=10L but no success.

len <- 30
fibvals <- numeric(len)
fibvals[1] <- 1
fibvals[2] <- 1
for (i in 3:len) { 
  fibvals[i] <- fibvals[i-1]+fibvals[i-2]
} 
for (i in 1:length(fibvals)){
  if(fibvals[i] > 1000){print(head(fibvals[i],n=10L))}
}

I expect the first 10 fibvals to show, but it keeps showing me up to my len = 30 (so 4 extra)

1 Answers1

0

an other approach using a while-loop

#initialisation
m <- matrix( data = c(1,1), nrow = 2 )
n = 10
limit = 1000

#add new row to m,
# until m contains 10 (n) values above 1000 (limit)
while(length(m[ m > limit]) < n ){ 
  m <- rbind( m, m[length(m)] + m[length(m)-1] )
}
#print the values above the limit
print( m[m>limit] )
Wimpel
  • 26,031
  • 1
  • 20
  • 37