Fibonnaci numbers in Javascript

Two simple functions for generating the first n Fibonnaci numbers. Compare the recursive function with the iterative one. What memory and efficiency issues would need to be addressed for large values of n?


"use strict";

var fib_recurse = function (n) {
  var s =[];

  if (n===1) {
    return [0, 1];
  } 
  else {
    s = fib_recurse(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
};


var fib_iterate = function (n) {
    var i, s=[0,1];

    for (i=0; i < n-1; i += 1) {
        s.push(s[s.length - 1] + s[s.length - 2]);
    }

    return s;
};

console.log(fib_recurse(20));
console.log(fib_iterate(20));
Advertisements

Blog at WordPress.com.

Up ↑