DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 114

The task is to find the n-th Fibonacci number.

The boilerplate code

function fib(n) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Fibonacci numbers are the sum of the previous 2 numbers in the Fibonacci sequence. It starts from 0, 1,..., then the addition starts.

If the n-th Fibonacci number is less than or equal to 1, return the value of n

if(n <= 1) return n;
Enter fullscreen mode Exit fullscreen mode

Create the variables of the numbers to be added

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

To find the n-th number, keep adding the previous and the current number till n is reached

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

After addition, the current becomes the previous, and the next becomes the current, till n is reached.

The final code

function fib(n) {
  // your code here
  if(n <= 1) return n;

  let prev = 0;
  let curr = 1;

  for(let i = 2; i <= n; i++) {
    const next = prev + curr;
    prev = curr;
    curr = next;
  }

  return curr;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)