...

/

Solution Review: Corresponding Fibonacci Number

Solution Review: Corresponding Fibonacci Number

This review provides a detailed analysis of the ways to find the corresponding element at a given index in the Fibonacci series.

Solution #1: Iterative Method

Press + to interact
function fibonacci(testVariable) {
var fn0 = 0;
var fn1 = 1;
for (let i = 0; i < testVariable; i++) {
var temp = fn0 + fn1;
// Setting variables for next iteration
fn0 = fn1;
fn1 = temp;
}
return fn0;
}
// Driver Code
var testVariable = 7;
console.log(fibonacci(testVariable));

Explanation

In the iterative method, we keep track of the two previous elements using the variables fn0 and fn1. Initially, the values of the two variables are:

fn0 = 0;
fn1 = 1;

However, in each iteration, the values are updated in the following way:

Solution #2: Recursive Method

Press + to interact
function fibonacci(testVariable) {
// Base case
if (testVariable <= 1) {
return testVariable;
}
// Recursive case
return(fibonacci(testVariable - 1) + fibonacci(testVariable - 2));
}
// Driver Code
var testVariable = 7;
console.log(fibonacci(testVariable));

Explanation:

In the code above, the function fibonacci() is a recursive function as it calls itself in the function body.

The base case of the function (line number 3) deals with the two initial values, i.e, for index 00 the value is ...