Theory behind fibonacciSTEP 1 - what is our goal?step 2 - write code! |
Fibonacci Sequence looks like this:
1, 1, 2, 3, 5, 8, 13, 21, 24 The logic behind this is pretty straightforward First two numbers are the same but the next number is a sum of the previous 2. 1 0 + 1 = 1 1+ 1 = 2 1 + 2 = 3 2 + 3 = 5 3 + 5 = 8 5 + 8 = 13 8 + 13 = 21 13 + 21 = 34 Doesn't this look like recursion? It does. If you are asking WHAT the hell is recursion? It is a brilliant question because the first time I got asked that was on an interview. If anyone asks you what is this? Just say answer it is a function that executes itself. Scratching your heads? Analogy is Russian nesting dolls. You have a big wooden doll then you open it, there is another one smaller one, right? of course. you keep going until you get to that tiny one. But you are repeating exactly the same operation (opening the nesting dolls). The only difference is it is going from the biggest to the smallest size until the tiniest one cannot be opened.
Let's write code!!!! JavaScript Code
Let's say we have an sequence (1, 1, 2, 3, 5, 8, 13, 21, 34)
and we need an output from function Fibonacci(4) to return 3. Let's say we want to cheat and hardcode this as an array Your output is 5 not 3.
So we know that the first 2 numbers in Fibonacci sequence are 1 and 1, and you will get 1 and 1 output we need to right away include if condition
The very next thing we need to do some logical thinking. We know that position 1 and 2 which are less than 3 will yield 1, right so we need to add previous two positions.... So our else also includes return because we are not seeking any operations after else.
Code Editor
By the way Here is your console.log
console.log(fibonacci(0)); //0 console.log(fibonacci(1)); //0+1 console.log(fibonacci(2)); //0 + 1 + 1 console.log(fibonacci(3)); //2 + 1 console.log(fibonacci(4)); //1 + 3 console.log(fibonacci(5)); //4 + 1 console.log(fibonacci(40)); //102334155 Please DO NOT try to run 50 or anything above that. Your browser will freeze :) Fibonacci is part of Big O Notation O(2^n) That is coming up soon! |