Sum of All Odd Fibonacci Numbers Challenge

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

Challenge Guide

freeCodeCamp Challenge Guide: Sum All Odd Fibonacci Numbers

Solution from the challenge guide.


function sumFibs(num) {
let prevNumber = 0;
let currNumber = 1;
let result = [];
while (currNumber <= num) {
  if (currNumber % 2 !== 0) {
    result.push(currNumber);
  }
  currNumber += prevNumber;
  prevNumber = currNumber - prevNumber;
}

return result;
}

Please I need an explanation of why prevNumber is assigned to currNumber - prevNumber in the while loop. That’s where I’m confused.

I added a tmp variable: let tmp = currNumber + prevNumber;
The value of prev in each loop is equal to curr: prevNumber = currNumber;

function sumFibs(num) {
    let prevNumber = 0;
    let currNumber = 1;
    let result = [];
    while (currNumber <= num) {
        if (currNumber % 2 !== 0) {
            result.push(currNumber);
        }
        
        let tmp = currNumber + prevNumber;
        prevNumber = currNumber;
        currNumber = tmp;
    }
    return result;
}

Please I don’t understand your solution.

You can do a simulation by hand, e.g. try to calculate sumFibs(10) or so. Look at the while-loop and watch how currNumber and prevNumber change.

Only looking at the program lines and try to understand them is sometimes not enough, you have to see how the algorithm works (so the idea is doing a simulation).

1 Like

Thank you. That’ll make me understand better.

I just changed these lines of code:

let tmp = currNumber + prevNumber;
 prevNumber = currNumber;
 currNumber = tmp;

The Fibonacci sequence is as follows:
0, 1, 1, 2, 3, 5, 8
In the first run prev is zero.
In the first run, curNumber is 1. So we have:
0, 1
The next value of currNumber is the sum of currNumber, which is 1, and its previous value, prev, is zero. I kept the sum in a tmp variable.
Why did I keep it in the tmp variable?
Because the value of prev in each loop is equal to currNumer, it means that prev will be one block ahead. Finally, the currNumber value is updated for the next loop.