It is very common interview question i see in many places:
write a function which receives a serial number as a parameter and returns a fibonacci number.
// num -> 1 => 0
// num -> 2 => 1
// num -> 3 => 1
// num -> 4 => 2
// num -> 5 => 3
Usually i was quickly writing an answer using a recursion:
function f(num) {
if (num === 0) return 0;
if (num === 1 || num === 2 || num === 3) return 1;
return f(num - 1) + f(num - 2);
}
console.log(f(5))
But ,since i found out that recursion has much more space complexity than iterative way,
Here is that i come with trying to implement the fibonacci challenge using iterations (of while loop):
function f(num) {
if (num === 1) return 0;
if (num === 2 || num === 3) return 1;
let counter = 4; // important to begin from 4, because we already taked care of 1 and 2 and 3
let result = 1, old = 1;
while (counter <= num) {
let temp = result;
result = old + result;
counter++;
old = temp;
}
return result;
}
let num = 1;
console.log(`${num} => ${f(num)}`)
No comments:
Post a Comment