freeCodeCamp Algorithm Challenge Guide: Sum All Odd Fibonacci Numbers

freeCodeCamp Algorithm Challenge Guide: Sum All Odd Fibonacci Numbers
0

#1

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

:checkered_flag: 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

:speech_balloon: 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.

try to solve the problem now

:speech_balloon: Hint: 2

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

try to solve the problem now

:speech_balloon: 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.

try to solve the problem now

Spoiler Alert!

687474703a2f2f7777772e796f75726472756d2e636f6d2f796f75726472756d2f696d616765732f323030372f31302f31302f7265645f7761726e696e675f7369676e5f322e676966.gif

Solution ahead!

:beginner: Basic Code Solution:

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

        currNumber += prevNumber;
        prevNumber = currNumber - prevNumber;
    }

    return result;
}

// test here
sumFibs(4);

:rocket: Run Code

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 even, add it to the result.
  • Complete the Fibonacci circle by rotating getting the next number and swapping values after.
  • Return the result.

Relevant Links

:sunflower: Intermediate Code Solution:

function sumFibs(num) {
  // create an array of fib numbers till num
  var arrFib = [1];
  for (var i = 1; i <=num;) {
      arrFib.push(i);
      i = arrFib[arrFib.length - 1] + arrFib[arrFib.length - 2];
  }

  // return the sum of odd numbers from the array
  var res = arrFib.reduce(function(prev, curr) {
      if (curr%2 !== 0) return prev + curr;
      else return prev;
    });

  return res;
}

// test here
sumFibs(4);

:rocket: Run Code

Code Explanation:

  • Create an array of fibonacci numbers till num.
  • Use reduce() method to find the sum of odd members of array.
  • Return the sum.

Relevant Links

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.


#2

#3

#4

my code keep on freezing browser.


#5

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


#6

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


#8

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


#10

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


#11

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


#13

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.


#14

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;
}

#15

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);


#16

use this:


#17
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;
}

#18

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);

#19

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


#20

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);

#21
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);

#22
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.


#23

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