Nth element of the Fibonacci series JavaScript


In this problem statement, our aim is to find the nth element in the fibonacci series with the help of Javascript functionalities. To solve this problem we will use a recursive technique.

Understanding the problem statement

The problem is to write a function in Javascript that will help find the nth number in the fibonacci sequence. For example, if we want to know the 3rd number in the fibonacci series then the 3rd number is 2.

What is the Fibonacci series?

The Fibonacci sequence is the chain of numbers in which each number is the sum of previous numbers. The series starts from 0 and 1 and the next numbers are obtained by summing up previous two numbers. So first few numbers of the Fibonacci series is as follows −

0, 1, 1, 2, 3, 5, 8, 13,......

Logic for the given problem

For implementing the code for the above problem we will use recursion to find the nth element of the Fibonacci series. If n is less than 2 then the function will return n, otherwise it will call itself twice with n-1 and n-2 as parameters and return the sum of the two results.

Algorithm

Step 1 − Declare a function called fibonacci which is using an argument of number n. This number n is the position of the number we have to find out.

Step 2 − Inside the function, check the condition if n is less than 2 then return n. Because there are starting numbers 0 and 1.

Step 3 − Otherwise return the sum of n-1 and n-2 by calling the above function recursively.

Step 4 − Return the result as the nth number of the Fibonacci sequence.

Code for the algorithm

//function to find the nth number from fibonacci series
function fibonacci(n) {
   if (n < 2) {
      return n;
   } else {
      return fibonacci(n - 1) + fibonacci(n - 2);
   }
}
// Example usage
console.log(fibonacci(6));
console.log(fibonacci(10));

Complexity

The time complexity for the created code is O(2^n) because every recursive call creates a branch into two more recursive calls. So as a result this algorithm is not efficient for large values of n.

Conclusion

So the above created function can be used to find out the nth number in the Fibonacci series with the time complexity O(2^n). We have basically used recursive technique to find out the required number of Fibonacci sequence.

Updated on: 18-May-2023

738 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements