Failing last test in Fibonnaci

Hello Nice Community,

Could you please help me to understand why is my code failing in the last test?

  **Your code so far**

function sumFibs(num) {
let i = 2;
var fNumber = 0;
var sNumber = 1;
var array = [];
var secondArr = [];
var thirdArr = [];
var total = 0;
array.push(fNumber);
array.push(sNumber);
secondArr.push(fNumber);
secondArr.push(sNumber);

for (i = 2; i <= num; i++) {
array[i] = array[i - 2] + array[i - 1];
  if(array[i] < num){
    secondArr.push(array[i]);
    }
}

secondArr.map(item => {if(item%2>0){
  thirdArr.push(item);
  total = total + item;
}})
console.log(thirdArr);
console.log(total);
return total;
}

console.log(sumFibs(75025));
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36.

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

Off by one error.


As a side note, this is a really inefficient approach, building three different arrays. I’d think about how you can solve this problem while using zero arrays while also only computing the exact number of Fibonacci numbers you need to check.

Thanks Jeremy, very accurate your advice,

I would love to know how to solve the challenge without all those arrays, but brain just can think of a better solution, do you know how can I develop that skill?

Honestly, the way I learned was to try stuff, show people my code, and have them give me feedback.


In this case, your code has three “parts”:

  1. Compute a Fibonacci
array[i] = array[i - 2] + array[i - 1];
  1. Check the size of the Fibonacci
    secondArr.push(array[i]);
  1. Check the 'even/odd’ness of the Fibonacci
if(item%2>0) {
//...
  total = total + item;

Why do them separately?


In general, my advice is

a) Recompute as little as possible
b) Store as little as possible
c) If you compute it more than once, consider storing it
d) If you only use it once, consider not storing it


So here I’d start by making only one loop that computes the Fibonacci, check its size, and checks it’s 'even/odd’ness. Once you get down to one loop, then you can think about how to store less stuff.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.