Last active
August 29, 2015 14:08
-
-
Save johnelliott/111c639020306d075f2f to your computer and use it in GitHub Desktop.
Project Euler #2
This file contains hidden or 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
// Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: | |
// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... | |
// By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. | |
// function makeFibsArray (howManyFibs) { | |
// var fibsArray = [1,2]; | |
// for (var i = fibsArray.length - 1; i<=howManyFibs; i++) { | |
// fibsArray.push(findNextFibInArray(fibsArray)); | |
// } | |
// return fibsArray; | |
// } | |
function findNextFibInArray (array) { | |
return (array[array.length-2] + array[array.length-1]); | |
} | |
function makeFibsArrayUnder(topFib) { | |
var fibsArray = [1,2]; | |
for (var i = fibsArray.length - 1; fibsArray[i]<topFib; i++) { | |
fibsArray.push(findNextFibInArray(fibsArray.slice([fibsArray.length, fibsArray.length+1]))); | |
} | |
return fibsArray; | |
} | |
function addUpEvensInArray (array) { | |
var total = 0; | |
for (var i = array.length - 1; i >= 0; i--) { | |
if (array[i] % 2 === 0) { | |
total += array[i]; | |
} | |
} | |
return total; | |
} | |
function solve () { | |
return addUpEvensInArray(makeFibsArrayUnder(4000000)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment