-2

I tried playing around with recursion in javascript. I wrote a function for the Fibonacci sequence. However, if only works if the argument is 0

fib = (x)=>{
    if (x == 0 || x ==1) {
        return 1
    } else {
        return fib(x-1) + fib(x+1)
    }
}

It returns 1 for 1, but a number above 0 I get the error maximum call stack size exceeded

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Osborne Saka
  • 469
  • 1
  • 4
  • 21
  • 3
    Try to write down the calculation with a pen and paper and see where it goes wrong or add logs or use the debugger. Hint: fib(x+1) is a bigger problem and not a smaller one :) – Benjamin Gruenbaum Apr 12 '19 at 19:02

2 Answers2

2

This is not the Fibonacci sequence. This is the Fibonacci sequence:

fib = (x) => {
  if (x == 0 || x == 1) {
    return 1;
  } else {
    return fib(x - 1) + fib(x - 2);
  }
}

for (let i = 0; i < 10; i++) {
  console.log(fib(i));
}

In its simplest form, of course. If you go too far beyond 10, you'll experience what an exponential cost of computation can do to a computer.

mbojko
  • 13,503
  • 1
  • 16
  • 26
1

You need the value of the second last iteration, no an iteration ahead.

Please have a look here, too: Fibonacci number.

const fib = x => {
    if (x === 0 || x === 1) {
        return 1;
    }
    return fib(x - 2) + fib(x - 1);
};

console.log(fib(7));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392