Wednesday, 7 December 2011

fibonacci number in javascript under cached way

function fibonacci(n) {
    if (!(n in fibonacci)) {
        if (n == 0) {
           fibonacci.counter++;

           fibonacci[n] = 0;
           return 0;
         }

         if (n == 1) {
            fibonacci.counter++;

            fibonacci[0] = 0;
            fibonacci[1] = 1;
            return 1;
          }
        
          fibonacci.counter++;

          fibonacci[n] = fibonacci(n -1) + fibonacci(n-2);
     }
  
     return fibonacci[n];
}
fibonacci.counter = 0; // for debug
var val1 = fibonacci(10);
var val1 = fibonacci(9);
console.log('counter: ' + fibonacci.counter); // >> counter: 10
var val1 = fibonacci(11);
console.log('counter: ' + fibonacci.counter); // >> counter: 11

No comments:

Post a Comment