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;

for (i = 2; i <= num; i++) {
array[i] = array[i - 2] + array[i - 1];
  if(array[i] < num){
} => {if(item%2>0){
  total = total + item;
return total;

  **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
  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.