0

I'm trying to create a simple program in javascript where the Fibonacci square can be created by a random number sequence but I can't seem to connect both parts of my code. The first side being: the call for a random number and the second part: calculating the Fibonacci square.

var n = function getRandomNum() {
     return Math.floor(Math.random()*100) +1;
  }



function fib(x) {
  if (x < 2) {
    return x;
  } else {
    return fib(x - 1) + fib(x - 2);
  }
}
 console.log(fib(n));

Tell me where I'm going wrong. These are the errors I get when I run it.

RangeError: Maximum call stack size exceeded
    at fib:7:13
    at fib:11:12
    at fib:11:12
    at fib:11:12
    at fib:11:12
    at fib:11:12
  • 1
    you assign the function `getRandomNum` to `n` and not the return value of calling that function. Write `function getRandomNum() { ... }, var n = getRandomNum();` – le_m Dec 10 '17 at 23:37
  • 3
    `n` is a function - you're not calling `n` – Jaromanda X Dec 10 '17 at 23:37

2 Answers2

0

Aside from not invoking the random number generator, you're using a very poorly optimized algorithm. If you think through all the redundant calls that need to take place, you'll see why the stack limit is reached.

var n = function getRandomNum() {
  return Math.floor(Math.random() * 100) + 1;
}(); // <-- quick inline invocation... not normally how you'd use this.

console.log(n);

function fib(x) {
  function _fib(x, a, b) {
    if (x < 2) {
      return a;
    }
    return _fib(x - 1, b, a + b);
  }

  return _fib(x, 0, 1);
}
console.log(fib(n));
0

Since you don't call n function, you should call it like the following.

var n = function getRandomNum() {
     return Math.floor(Math.random()*100) +1;
  }



function fib(x) {
  if (x < 2) {
    return x;
  } else {
    return fib(x - 1) + fib(x - 2);
  }
}
 console.log(fib(n));

But, there's a huge problem in your code, as @rock star mentioned, there's no any optimizing process in your code. That is why your code has caused the problem on memory leak

To avoid this, you can simply use memoization, click this link you don't have any clue on it. Javascript Memoization Explanation?


So, your code can be improved like the folloiwng, by adapting memoization algorithm.

var n = function getRandomNum() {
     return Math.floor(Math.random()*100) +1;
  }

var result = [];
result[0] = 1;
result[1] = 1;

function fib(x) {
  var ix, ixLen;
  for(ix = 0, ixLen = x; ix < ixLen; ix++){
    if(!result[ix]){
      result[ix] = result[ix-2] + result[ix-1];
    }
  }
  console.log('n:', x, ' result: ', result[ix-1]);
  return result[ix-1];
}
console.log(fib(n()));

Compare the result with this site.
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html

moon
  • 640
  • 6
  • 14