Created
June 14, 2014 14:16
-
-
Save bencoveney/84cf817f34ca9d3aeb46 to your computer and use it in GitHub Desktop.
Even Fibonacci Numbers
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
var fibonacci = [1,2]; // seed numbers | |
var sum = 2; // sum of even seed numbers | |
var limit = 4000000; // 4 million limit | |
// Generate the next fibonacci number | |
var nextNumber = fibonacci[0] + fibonacci[1]; | |
// generate fibonacci numbers until the limit is reached | |
while(nextNumber < limit) | |
{ | |
// If the number is even, add it to the sum | |
if(nextNumber % 2 === 0) | |
{ | |
console.log(nextNumber + " is even"); | |
sum += nextNumber; | |
console.log("Sum is now " + sum); | |
} | |
// add the number to the sequence | |
fibonacci.push(nextNumber); | |
// The next number in the sequence is the sum of the previous two numbers | |
var nextNumber = fibonacci[fibonacci.length - 1] + fibonacci[fibonacci.length - 2] | |
console.log("Generated " + nextNumber); | |
} | |
// Return the result | |
console.log("Total is " + sum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment