freeCodeCamp Challenge Guide: Sum All Odd Fibonacci Numbers

Sum All Odd Fibonacci Numbers


Problem Explanation

You will need to gather all the Fibonacci numbers and then check for the odd ones. Once you get the odd ones then you will add them all. The last number should be the number given as a parameter if it actually happens to be an off Fibonacci number.

Relevant Links


Hints

Hint 1

To get the next number of the series, you need to add the current one to the previous and that will give you the next one.

Hint 2

To check if a number is even all you have to check is if number % 2 == 0.

Hint 3

As you get the next odd one, don’t forget to add it to a global variable that can be returned at the end. result += currNumber; will do the trick.


Solutions

Solution 1 (Click to Show/Hide)
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);

Code Explanation

  • Create a variable to keep record of the current and previous numbers along with the result that will be returned.
  • Use a while loop to make sure we do not go over the number given as parameter.
  • We use the modulo operand to check if the current number is odd or even. If it is odd, add it to the result.
  • Complete the Fibonacci circle by rotating getting the next number and swapping values after.
  • Return the result.

Relevant Links

Solution 2 (Click to Show/Hide)
function sumFibs(num) {
  // Perform checks for the validity of the input
  if (num <= 0) return 0;

  // Create an array of fib numbers till num
  const arrFib = [1, 1];
  let nextFib = 0;

  // We put the new Fibonacci numbers to the front so we
  // don't need to calculate the length of the array on each
  // iteration
  while ((nextFib = arrFib[0] + arrFib[1]) <= num) {
    arrFib.unshift(nextFib);
  }

  // We filter the array to get the odd numbers and reduce them to get their sum.
  return arrFib.filter(x => x % 2 != 0).reduce((a, b) => a + b);
}

// test here
sumFibs(4);

Code Explanation

  • Create an array of fibonacci numbers till num.
  • Use filter() method to filter out even numbers.
  • Use reduce() method to sum the remaining (odd) values.
  • Return the sum.

Note that this solution will be slower than Solution 1, as dynamically creating an array is rather slow, especially in JavaScript.

Relevant Links

Solution 3 (Click to Show/Hide)
function sumFibs(num) {
  // Every third Fibbonaci number is even
  //   and the rest are odd
  let f0 = 0;
  let f1 = 1;
  let f2 = 1;

  // Generate triples until num is reached
  let sum = 0;
  while (f1 <= num) {
    // Update sum
    sum += f1;
    if (f2 <= num) sum += f2;

    // Compute next three Fibonacci numbers
    [f0, f1] = [f1 + f2, f2 + (f1 + f2)];
    f2 = f0 + f1;
  }

  return sum;
}

Code Explanation

General idea

It is a property of Fibonacci numbers that every third number in the sequence is even and the rest are odd.

Algorithm

  • Use three work variables to hold the the current 3 Fibonacci numbers
  • Generate triples as long as the first odd value is less than num
  • Add the two odd values, f1 and f2, to the running sum of odd Fibonacci numbers
92 Likes

my code keep on freezing browser.

19 Likes

It sounds like you have accidentally created an infinite loop. You’ll need to manually fix your browser by deleting the solution from your browser’s local storage: http://forum.freecodecamp.com/t/clear-specific-values-from-your-browser-local-storage/19128

11 Likes

I followed the instruction, but i still have issues: here is a code that i was just trying to test

function sumFibs(num) {
var fibs=[];
for(var i=0 ; i< num ;i++){
fibs.push(i);
}

return fibs;
}

sumFibs(4);

is there anything wrong with that code? I just don’t understand why the code didn’t stop when i=4

1 Like

I know what you meant, my problem is that when i run that my browser freeze, and i just could not understand why.

2 Likes

Good to know that. At least now I know it works on your console. There has to be something wrong with my browser. Thanks

1 Like

Is there any online IDE that i could test this out?

1 Like

Oh really i didn’t know that was the case. I got really frustrated with my browser for a few days. thanks for pointing this out.

2 Likes

I’m curious, I finished the problem with a solution similar to the Basic one posted above, but instead of using an IF statement to check if the value was even or odd, I used modulo and used the remainder of the number % 2 times the number to get the sum of all the odd numbers and it got me wondering which of these operations would be more efficient, assuming that the efficiency really mattered.

my code:

function sumFibs(num) {
  if(num < 0) {
    return undefined;
  }
  var sumOdds = 0; // Sum of all odd fib numbers
  for(var n1 = 0, n2 = 1, temp; n2 <= num; temp = n2, n2 += n1, n1 = temp) {
    sumOdds += n2 * (n2 % 2);
  }
  return sumOdds;
}
30 Likes

Solution -

function sumFibs(num) {

var fib = [];

for (var i =0; i < num; i++){
if (i ===0){
fib[i] = 1;
}
if (i ===1){
fib[i] = 1;
}
}

for (var j =2; j < num; j++){
fib[j] = fib[j-2] + fib[j-1];
}
var sumOdd = fib.filter(function(val){
return val%2 !==0 && val <= num;
});

return sumOdd.reduce(function(a, b){
return a+b;
});

}

sumFibs(1000);

1 Like

use this:

1 Like
function sumFibs(num) {
  var a = 1, b = 1;
  var sum = 2;
  
  var tmp = a + b;
  while (tmp <= num) {
    if ((tmp % 2 !== 0) && (tmp <= num)) {
      sum += tmp;
    }
    a = b;
    b = tmp;
    tmp = a + b;
  }
  
  return sum;
}
17 Likes

Here’s an alternate basic solution:

function sumFibs(num) {
  
  var a = 1, b = 1, sum = 0;
  
  while (a <= num && b <= num) {
     if (a%2 !== 0)
       sum+=a;
     if (b%2 !== 0)
       sum+=b;
     a = a + b;
     b = a + b;
 }
   if(a<=num && a%2 !== 0) /* this means b >=num but a<=num */
         sum += a;
  else if(b <= num && b%2 !== 0) /* this means a>=num but b<=num*/
         sum += b;
     
  
  return sum;
}

sumFibs(75025);
3 Likes

There is typo in the code explanation above, please change ‘even’ to ‘odd’

1 Like

Basic solution with comments for clarification.

function sumFibs(num) {
  var prevNumber = 0; //creates variable prevNumber with value 0
  var currNumber = 1;//create variable currNumber with value 1
  var result = 0;//creates variable result with value 0
  while (currNumber <=num){ //while curr is less than or equal to the given sumFibs number...
if (currNumber % 2 !== 0){ //if the remainder when divided by two is NOT 0...
  result += currNumber; //...add that number to result
}
currNumber += prevNumber; //make currNumber equal to currNUmber plus prevNumber
prevNumber = currNumber - prevNumber;//make prevNumber equal to new currNumber minus the old prevNumber
  }
  return result; //return the result
}

sumFibs(4000000);
4 Likes
function sumFibs(num) {
  var mySequence = [1, 1];
  var sequenceOfOdds = [1, 1];
  var i = 1;
  
  do {
    i = mySequence[mySequence.length-1] + mySequence[mySequence.length-2];
    if (i <= num) {
      mySequence.push(i);
      if (i % 2 !== 0) sequenceOfOdds.push(i);
    }
  } while(i < num);
  

  return sequenceOfOdds.reduce(function(a, b) { return a+b; });
}

sumFibs(4);
2 Likes
function sumFibs(num) {
  
  var fiboArray = [1, 1, 2]; 
  //Initialize array with #s to avoid infinite loop
  var fibo = 0;
  var currentVal = 2; //Set sum of first 2 odd numbers
  
  for (var i = 2; fiboArray[i] <= num; i++) {
    //Loop through array, conditional stop is current fibonacci #       less than or equal to given value
    fibo = fiboArray[i] + fiboArray[i - 1];
    //Add next fibonacci # to array
    fiboArray.push(fibo);
    
    if (fiboArray[i] % 2 === 1) { 
      //If current fibonacci number is odd, add it to sum
      currentVal += fiboArray[i];
    }
  }

  return currentVal;
}

I wanted to use an array to keep track of my Fibonacci sequence, but I had a hard time getting past the infinite loop created by the first two numbers.

2 Likes

In Basic Code Solution this should be If it is odd or If it isn’t even