DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 56

The task is to implement a function that generates a Fibonacci number.

The boilerplate code:

function fib(n){
  if (n === 0) return 0
  if (n === 1) return 1
  return fib(n - 1) + fib(n - 2)
}
Enter fullscreen mode Exit fullscreen mode

The fibonacci sequence starts with ) as the 0th number, and 1 as the 1st number. Every subsequent number is a sum of the previous two.

Start with two variables. One that holds the previous fibonacci number, and one that holds the next fibonacci number.

let prev = 0, curr = 1
Enter fullscreen mode Exit fullscreen mode

Repeatedly update them. The next number is a sum of the previous two.

for(let i = 2, i <= n, i++) {
let next = prev + curr
}
Enter fullscreen mode Exit fullscreen mode

The current becomes the previous, the next becomes the current.

prev = curr
curr = next
Enter fullscreen mode Exit fullscreen mode

This is done till the desired position is reached.

The final code

function fib(n){
  if(n < 0) return undefined;
  if (n === 0) return 0;
  if (n === 1) return 1;

  let prev = 0, curr = 1;

  for(let i = 2; i <= n; i++) {
    let next = prev + curr;
    prev = curr;
    curr = next;
  }
  return curr
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)