In: Computer Science
The Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21…… starts with two 1s, and each term afterward is the sum of its two predecessors. Please write a function, Fib(n), which takes n as the input parameter. It will return the n-th number in the Fibonacci sequence. Using R, the output for Fib(9) should give only the 9th element in the sequence and not any of the previous elements. Please Help :)
SOURCE CODE: in R language
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly
indented for better understanding.
==========
Fib <- function(nterms)
{
# first two terms
n1 = 1
n2 = 1
count = 2
while(count < nterms)
{
# Calculate the sum of last two numbers
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count = count + 1
}
# Return the nth fibonacci number
return (nth)
}
# test the function here with different values
print(Fib(5))
print(Fib(7))
print(Fib(10))
print(Fib(15))
===================