Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 25, 2018 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/e52421d9e866e1e5c0211c7cd9dc43a2 to your computer and use it in GitHub Desktop.
Save nickihastings/e52421d9e866e1e5c0211c7cd9dc43a2 to your computer and use it in GitHub Desktop.
Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num. The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8. For example, sumFibs(10…
function sumFibs(num) {
//set up variables a counter to hold the next Fibonacci number and an
//array to hold all the Fibonacci numbers below num.
var count = 0;
var fib = [1, 1];
//loop through and keep adding Fibonacci numbers to the array until the num is reached
for(var i = 0; i<fib.length; i++){
count = fib[i] + fib[i+1];
if(count <= num ){
fib.push(count);
}
}
//Find the sum of all the odd fibonacci numbers below num by reducing the fib array
//check the current number is not even using modulo and add it to the total if it's not.
var sum = fib.reduce(function(total, current){
if(current % 2 !== 0){
return total + current;
}
return total;
}, 0);
//set the original total value to 0.
// return the final total.
return sum;
}
sumFibs(4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment