In: Statistics and Probability
Fibonacci
Write pseudocode to calculate F(n)
Write pseudocode to construct a vector of the first n numbers in the Fibonacci
sequence.
Write a function:
fibo(n = 1){
# Your code here
}
which takes one parameter n and returns the nth fibonacci number.
Use the function you wrote to calculate the 58th Fibonacci number. Include your
R code in your report
The Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) is defined as F(1) = 1, F(2) = 1, F(n) = F(n-1) + F(n-2).
I need the R studio using R markdown code for this
We are essentially required to compute Fibonacci numbers and add the Fibonacci numbers to a vector, and also define a function to calculate the Fibonacci number for any number 'n' we desire.
Using this function, we must then compute the 58th Fibonacci number.
A Fibonacci sequence is a sequence whose nth value is a sum of the (n-1)th and the (n-2)th value.
Thus, to add Fibonacci numbers to a vector, we can use a for-loop. The value of 'n' can be defined by the user. The code is:
n=5
# Dummy value of n
fibo=vector("numeric",n)
# Intitializing fibo vector as an empty vector
for(i in 1:n){
if(i==1){
fibo[i]=1
}else if(i==2){
fibo[i]=1
}else{
fibo[i]=fibo[i-1]+fibo[i-2]
}
}
# Defining a for loop which will keep adding the values as required
In the above code, you just have to change the value of n, and you will get a vector of Fibonacci numbers till that value of n.
Below is the code for defining a function to compute Fibonacci numbers:
fibo_cal= function(n){
if(n==1){
return(1)
}else if(n==2){
return(1)
}else{
return(fibo_cal(n-1)+fibo_cal(n-2))
}
}
fibo_cal(58)
Above is the code to compute the Fibonacci number at a specific point. fibo_cal is the name of the function we have defined, and typing in fibo_cal(58) will give us the 58th Fibonacci number.
If you have any doubts, please let me know in the comments and I
will get back to you. Happy learning!