Fibonnaci sum all odds algorithm - question

Hi,

For this exercise, how do I find out all values up to the one passed into the function? For the first for loop, I am using num as the value up to in the condition but I think that is setting the length of the array to generate and store up to and not creating values up to it.

function sumFibs(num) {
  var fiboArr = []
  const reducer = (accumulator, currentValue) => accumulator + currentValue

  //generate fibonacci sequence to
  //populate array with numbers up to argument
  for(let i=1; i<num; i++) {
    fiboArr[0]=1
    fiboArr[1]=1
    fiboArr[i+1] = fiboArr[i] + fiboArr[i-1];
    fiboArr.push([i+1]);
  }
  //remove even numbers
  for(let j=0; j<fiboArr.length; j++) {
    if(fiboArr[j]%2==0){
      fiboArr.pop([j]);
    }
  }
   return fiboArr.reduce(reducer);
}

With the following test cases, they do not pass:

sumFibs(5); //expect 10, receiving 12; array before sum is [ 1, 1, 2, 3, 5 ]
sumFibs(10); //expect 10, receiving 88; arrau before sum is [ 1, 1, 2, 3, 5, 8, 13, 21, 34 ]

You are correct,

this creates num Fibonacci numbers.

I would pick a loop condition that stops when the most recently generated Fibonacci number is larger than num.


As a side note, your code will run much faster if you don’t use an array fiboArr.

Thanks, I did away with the array. Ran way faster for sure.

1 Like

Awesome! As a general rule of thumb for performance, only store data if you need the data later.

1 Like