Htet Phone Naing
Htet Phone Naing

Reputation: 1

Finding Fibonacci bugs keep returning undefined

I am trying to solve the fibonacci in recrusive way and I think i got a bug in my code.I can't figurer out where it is. Example: fib(4) === 3

function fib(n, array = [0, 1], count = 0) {
  if (n == 0) {
    return 0;
  }
  if (n == 1) {
    return 1;
  }

  array.push(array[count] + array[count + 1]);
  console.log(array)

  if (n === array.length-1) {

    return array.pop()
  }
  fib(n, array, count + 1);
}
let ans=fib(2)
console.log(ans)

Upvotes: 0

Views: 70

Answers (1)

sonEtLumiere
sonEtLumiere

Reputation: 4562

you can do by this way using recursion

  var i = 0, a = 0, b = 1, c = 0;
  var out = "";
 
  function fibonacci(n){
    i = 0;
    if(i < n){
     out += a + ",";
     c = a + b;
     a = b;
     b = c;
     i++;
     console.log(out);
     fibonacci(n - i); 
   }
  }

  fibonacci(10);

Upvotes: 1

Related Questions