Skip to content

Instantly share code, notes, and snippets.

@rickMcGavin
Created September 8, 2016 01:11
Show Gist options
  • Save rickMcGavin/4eadbf18002c93cdc00fb22bf05f7707 to your computer and use it in GitHub Desktop.
Save rickMcGavin/4eadbf18002c93cdc00fb22bf05f7707 to your computer and use it in GitHub Desktop.
// project euler 2
// 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.
// declare initial variables
var a = 0;
var b = 1;
var c = 0;
var sum = 0;
function evenFibSum(num) {
// while the fib number is less than 4 mil
while (c < num) {
// create next fib number by adding previous 2 fib numbers
c = a + b;
// reassign variables to make new previous 2 fib numbers
a = b;
b = c;
// check if fib num is even
if (c % 2 === 0) {
// if even add it to sum variable
sum += c;
}
}
// return the sum of even fibonacci numbers less than num
return sum;
}
// log the sum of even fib numbers to the console
console.log(evenFibSum(4000000)); // return 4613732
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment