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)
}
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
Repeatedly update them. The next number is a sum of the previous two.
for(let i = 2, i <= n, i++) {
let next = prev + curr
}
The current becomes the previous, the next becomes the current.
prev = curr
curr = next
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
}
That's all folks!
Top comments (0)