144k views
2 votes
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 :)

User Scarecrow
by
5.4k points

2 Answers

5 votes

Answer:

#Create a function Fib to return the nth term of the fibonacci series

#Method header declaration

Fib <- function(n) {

#when n <= 1, the fibonacci number is 1

#hence return 1

if (n <= 1)

return(1)

#when n = 2, the fibonacci number is 1

#hence return 1

else if (n == 2)

return(1)

#at other terms, fibonacci number is the sum of the previous two

#numbers.

#hence return the sum of the fibonacci of the previous two numbers

else

return( Fib(n-1) + Fib(n-2))

} #End of method.

============================================================

Sample Output:

A call to Fib(9) will give the following output:

>> 34

============================================================

Step-by-step explanation:

The above program has been written in R language and it contains comments explaining each of the lines of code. Please go through the comments in the code.

For readability, the actual lines of code have been written in bold face to distinguish them from the comments.

User Sroush
by
5.5k points
5 votes

9th value is 34

Step-by-step explanation:

R or Fib (n) function is given by: (n - 1) + (n - 2), where n is the number in the Fibonacci sequence .

Hence, fib (9) = (9 - 1) + (9 - 2)

= 8th value + 7th value on the sequence summed together

Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21. The 8th value is 21 and the 7th value is 13.

R = (n - 1) + (n - 2)

R (9) 0r Fib (9) = 21 + 13

= 34

User Tywana
by
5.1k points