In Javascript myFib Write a JavaScript function using recursion to compute the F
ID: 3701973 • Letter: I
Question
In Javascript
myFib
Write a JavaScript function using recursion to compute the Fibonacci number of n (where n is a positive integer). Your function should output the calculated result for the n given. You also need to type check to make sure the value being given is an integer.
Fib(n) = 1 for n = 0 or n = 1
Fib(n) = Fib(n-1) + Fib(n-2) for n > 1
These are the sample input and output that should be displayed:
console.log(myFib(5));
8
console.log(myFib(10));
89
console.log(myFib(8));
34
console.log(myFib(“Thirtyfive”));
Not an integer value!
console.log(myFib(3.5));
Not an integer value!
Explanation / Answer
Please find my implementation.
Please let me know in case of any issue.
<html>
<head>
<script>
// Function to produce the nth fibonacci
function myFib(n) {
// Check if the argument is an integer
if(n === parseInt(n,10)){
// Check if the number is less than or equal to 1
if (n <= 1){
return 1;
}
// If not then call the myFib recursively by decreasing n
else{
return myFib(n-2) + myFib(n-1);
}
}
// If number is not an integer return Not a integer
else
return "Not an integer value!";
}
// Calling of the myFib function
console.log(myFib(5));
console.log(myFib(10));
console.log(myFib(8));
console.log(myFib(3.5));
console.log(myFib('ThirtyFive'));
</script>
</head>
</html>
Please DONT forgot to rate my answer. We are working hard for you guys!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.