Friday, June 30, 2017

JavaScript Fibonacci

Here is a Fibonacci series code in JavaScript that uses Memoization technique of Dynamic Programming.

(function(){
  //suppose we want to find the first 10 terms
  'use strict';
  var fibArray = [];
  
  findFibByRec(10);
  
  function findFibByRec(number){
     for(var i = 0; i <= number; i++){
         console.log(fibRec(i));
     }
  }
  
  function fibRec(num){
     if(num == 0){
       fibArray[0] = 0;
       return 0;
     }
     
     if(num == 1 || num == 2){
       fibArray[num] = 1;
     }
     
     if(fibArray[num]){
        return fibArray[num];
     }
     
     if(!fibArray[num]){
       
       fibArray[num] = fibRec(num -1) + fibRec(num -2);
       return fibArray[num];
     }
  
  }

})()

No comments:

Post a Comment