Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created April 1, 2016 13:59
Show Gist options
  • Save vlad-bezden/1aec8d867b72a179719e87e18880bf16 to your computer and use it in GitHub Desktop.
Save vlad-bezden/1aec8d867b72a179719e87e18880bf16 to your computer and use it in GitHub Desktop.
Even Fibonacci Numbers

Even Fibonacci Numbers

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.

A Pen by Vlad Bezden on CodePen.

License.

'option strict';
function* fibonacci() {
let prev = 0,
curr = 1;
while (true) {
// this line will work, but it runs slower. Explicit assignment is much faster
//[prev, curr] = [curr, prev + curr];
prev = curr;
curr += prev
yield curr;
}
}
function runner(maxFibValue) {
let acc = 0,
value = 0;
for (let value of fibonacci()) {
if (value > maxFibValue) {
break;
} else if (value % 2 === 0) {
acc += value;
}
}
return acc;
}
startTime = performance.now();
const result = runner(4000000);
const stopTime = performance.now();
console.log(`Result: ${result}. Execution time: ${(stopTime - startTime).toFixed(4)} ms`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment