The task is to find the n-th Fibonacci number.
The boilerplate code
function fib(n) {
// your code here
}
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;
Create the variables of the numbers to be added
let prev = 0;
let curr = 1;
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;
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;
}
That's all folks!
Top comments (0)