Consider the while() loop below that computes all Fibonacci numbers less than 500. # fib1 and fib2 will represent the two latest terms in the sequence.
fib1 <- 1 # Initialize fib1
fib2 <- 1 # Initialize fib2
# Create the vector to store the output from the while loop.
full.fib <- c(fib1,fib2)
# While the sum of the last two terms is less than 500, execute the following commands.
while(fib1 + fib2 < 500){
# Save the latest term to old.fib2.
old.fib2 <- fib2
# Compute the sum of the latest two terms and assign the sum to be the new latest term.
fib2 <- fib1 + fib2
# Append the latest term to the end of the full.fib vector with all previous terms.
full.fib <- c(full.fib,fib2)
# Save the previously latest term (now the second to last term) to fib1.
fib1 <- old.fib2
}
# Print the output from the while loop.
full.fib
(a) The variable old.fib2 is not actually necessary. Rewrite the while() loop with the update of fib1 based on just the current values of fib1 and fib2.
(b) In fact, fib1 and fib2 are not necessary either. Rewrite the while() loop without using any variables except full.fib.
(c) Determine the number of Fibonacci numbers less than 1000000.