** Explanation Needed ** Sum All Odd Fibonacci Numbers

Link to challenge:

Solution code:

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

  return result;
}

// test here
sumFibs(4);

Could someone please explain the purpose of these last two lines of code to me?

currNumber += prevNumber;
prevNumber = currNumber - prevNumber;

In the guide, it says “Complete the Fibonacci circle by rotating getting the next number and swapping values after.”

I’m not sure what exactly do they do in the context of the challenge.

P.S: How do I add spoiler tags?

Well, lets look at a few specific cases:

let prevNumber = 0;
let currNumber = 1;

for (let i = 0; i < 5; i++) {
  console.log("i:", i);
  console.log(" start:\n    prevNumber = " + prevNumber + "\n    currNumber = " + currNumber);
  currNumber += prevNumber;
  prevNumber = currNumber - prevNumber;
  console.log(" end  :\n    prevNumber = " + prevNumber + "\n    currNumber = " + currNumber);
}

Output:

Summary
i: 0
 start:
    prevNumber = 0
    currNumber = 1
 end  :
    prevNumber = 1
    currNumber = 1
i: 1
 start:
    prevNumber = 1
    currNumber = 1
 end  :
    prevNumber = 1
    currNumber = 2
i: 2
 start:
    prevNumber = 1
    currNumber = 2
 end  :
    prevNumber = 2
    currNumber = 3
i: 3
 start:
    prevNumber = 2
    currNumber = 3
 end  :
    prevNumber = 3
    currNumber = 5
i: 4
 start:
    prevNumber = 3
    currNumber = 5
 end  :
    prevNumber = 5
    currNumber = 8

The formula for Fibonacci numbers is f(n) = f(n - 1) + f(n - 2).

This means that f(n - 1) = f(n) - f(n - 2).

Let’s call f(n) something else, like currNumber and let’s call f(n - 1) something else, like prevNumber. These two equations are what this solution is using.

1 Like