Kristina Bressler Kristina Bressler - 1 year ago 49
Javascript Question

How to limit Fibonacci Sequence in an array under a Number Javascript

I wrote a Fibonacci Sequence javascript solution. I was able to push out a Fibonacci Sequence array. However, this solution add an extra number in the array that is more than the limited number.

For example, if I want all the numbers in the array to be under 10, then the array should be [0, 1, 1, 2, 3, 5, 8]. However, with my solution, it still output the extra "13" in the array.



function fib(num) {
var x = 0;
var y = 1;
var fibarray = [0, 1];

while(y < num) {
y += x;
x = y - x;
fibarray.push(y);
}

return fibarray;
}
console.log(fib(10));





I don't understand why it output "13" when it shouldn't work as "13" is more than "10". Please help me fix this solution.

Dij Dij
Answer Source

It is happening because you are computing next y, pushing it to array and then checking if y is less than num or not but by then you have already added y to fibarray. Solution would be to check if y is less than num and then push it to fibarray and then compute next y and while condition is checked all over again.

function fib(num) {
var x = 0;
var y = 1;
var fibarray = [0];

while(y < num) {
    fibarray.push(y);
    y += x;
    x = y - x;
}

return fibarray;
}
console.log(fib(10));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download