The question for an algorithm is,
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Example 1:
Input: n=9
Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Example 2:
Input: n =5
Output: 0, 1, 1, 2, 3, 5
Let's start with the algorithm,
var fibonacci = function(n) {
var sequence = [0,1]
let currentValue = 1
let previousValue = 0
let iterationsCounter = n - 1;
while(iterationsCounter)
{
currentValue+=previousValue;
previousValue=currentValue-previousValue;
sequence.push(currentValue);
--iterationsCounter;
}
return sequence;
};
Here, we have taken the default sequence containing [0,1] because Fibonacci is the default two numbers 0 and 1 from where the sequence starts.
We have taken two variables storing current value and previous value which wehave taken in the sequence.
Then we have variable iterationsCounter which is used for looping till the iterationsCounter become zero.
Inside loop, we have added currentValue with previousValue to get the next value and stored in currentValue. Previous value becomes current value - previous value and after that we pushed current value in the sequence array. sequence array contins Fibonnaci Numbes.
I hope you understood the algorithm. If you have any doubts please let us know in the comments.
0 Comments