Posted by : Mostafa Mazhar
Problem name : Fibonacci number
Platform : leetcode
Language: Javascript
Language: Javascript
Link : fibonacci Number
In this problem you are given an index (n) and required to return the number on that index in the Fibonacci sequence.
The Fibonacci sequence is a simple sequence starts with (0 , 1) and then each number is the sum of the previous two numbers, so the sequence becomes : (0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ,.....etc.).
So for example if the given index is 7 the returned value is 13 .
remember: Computers always start counting from 0 not 1.
Algorithm:
- if the index is 1 or 0 the returned value will be the same as index itself.
- but if the index is larger we will need to create the Fibonacci sequence (fibSequance).
- we will create an array that have 0 and 1 as the first two elements.
- then we will loop through the array starting from the third element(2 as index).
- and we will push into the array the sum of the two previous elements (index (i-1) and (i-2)).
- at last we will return the element on the (n) index.