# More efficient way to code Fibonacci array?

More efficient way to code Fibonacci array?
0

#1

For the Sum Fibonacci Numbers exercise I used the following loop to generate my sequence:

``````  for (var i=0; i<33; i++) {
if (fibSequence[i] + fibSequence[i+1] <= num) {
fibSequence.push(fibSequence[i]+fibSequence[i+1]);
}
else {
break;
}
``````

I didn’t love the idea of hardcoding the limit of `i<33` and adding an if statement to limit the loop iterations. I have a feeling there is a more efficient way to code this, but it hasn’t come to me. Did anyone else come up with a better solution?

#2

maybe this ? :

``````  var fib = [1, 1];

while(fib[fib.length-1] <= num) {
var lastTwo = fib.slice(-2);
fib.push(lastTwo[0] + lastTwo[1]);
}
fib.pop(); // remove the last number which is beyond num
``````

#4

It did. So I first generated a Fibonacci sequence, then I removed any values divisible by 2 afterwards. Then used reduce to get the sum. Perhaps not the best way, but it made sense to me.

#5

A good exercice would be to do it in one step (computing the sum along the loop).But for now, good job