Created
March 25, 2018 19:09
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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