JavaScript

Fibonacci Series Program in JavaScript

In this tutorial, we are going to see how to calculate the Fibonacci sequence using the “for” loop as well as recursion.

The Fibonacci series is a sequence of integers of 0, 1, 1, 2, 3, 5, 8….

The first two terms are 0 and 1. All other terms are obtained by adding the two previous terms. This means that the nth term is the sum of the (n-1)th and (n-2)th term.
 

 

Fibonacci series using the “for” loop
function fibonacci(nbr) {

   var n1 = 0;
   var n2 = 1;
   var sum = 0;
 
   for(let i = 2; i <= nbr; i++){
      //sum of the last two numbers
      sum = n1 + n2; 

      //assign the last value to the first
      n1 = n2; 

      //assign the sum to the last
      n2 = sum; 
   }
 
   return nbr ? n2 : n1;
}

console.log(fibonacci(8));

Output:

21

Time complexity: O(n).
Space complexity: O(1).
 

 

Fibonacci series using recursion
function fibonacci(nbr) {
  if(nbr < 2){
    return nbr;
  }

  return fibonacci(nbr - 1) + fibonacci(nbr - 2);
}

console.log(fibonacci(8));

Output:

21

Time complexity: O(2^n).
Space complexity: O(n).
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *