Fibonacci Numbers

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation: F_{n} = F_{n-1} + F_{n-2} with seed values and F_0 = 0 and F_1 = 1 .

The Nth Fibonacci Number can be found using the recurrence relation shown above:

  • if n = 0, then return 0. 
  • If n = 1, then it should return 1. 
  • For n > 1, it should return Fn-1 + Fn-2

Example: In this example, we will find the nth Fibonacci Number using Recursion.

Javascript




// Javascript program for Fibonacci Series
// using Recursion
  
function Fib(n) {
    if (n <= 1) {
        return n;
    } else {
        return Fib(n - 1) + Fib(n - 2);
    }
}
  
// driver code
let n = 6;
console.log(n + "th Fibonacci Number: " + Fib(n));


Output

6th Fibonacci Number: 8


Applications of Recursion in JavaScript

Recursion is a programming technique in which a function calls itself directly or indirectly.  Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. Recursion is a technique in which we reduce the length of code and make it easy to read and write. A recursive function solves a problem by calling its own function and also calling for the smaller subproblem.

Recursion is a powerful technique that has many applications in the field of programming. Below are a few common applications of recursion that we frequently use:

  • Tree and graph traversal
  • Sorting algorithms
  • Divide-and-conquer algorithms
  • Sieve of Eratosthenes
  • Fibonacci Numbers

Let’s deep dive into each application:

Similar Reads

Tree traversal

The traversal of trees is very interesting, we can traverse trees in different ways. Recursion is also a very common way to traverse and manipulate tree structures....

Sorting algorithm

...

Divide-and-conquer algorithms

A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. There are various types of sorting. We are going to see insertion sort using recursion.Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands....

Sieve of Eratosthenes

...

Fibonacci Numbers

Divide and Conquer is an algorithmic paradigm in which the problem is solved using the Divide, Conquer, and Combine strategy....

Contact Us