Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ES6 version separating out the generation of the fibonacci sequence
- function * fibGen() {
- yield 1;
- yield 1;
- const lastTwo = [1, 1];
- while (true) {
- const next = lastTwo[0] + lastTwo[1];
- lastTwo.push(next);
- lastTwo.shift();
- yield next;
- }
- }
- function sumOddFib(n) {
- let total = 0;
- for (const fib of fibGen()) {
- if (fib >= n) break;
- total += fib % 2 ? fib : 0;
- }
- return total;
- }
- // ES5 version
- function sumOddFibV2(n) {
- if (n === 1) return 1;
- if (n === 2) return 2;
- var total = 2;
- var lastTwo = [1, 1];
- while (true) {
- var next = lastTwo[0] + lastTwo[1];
- lastTwo.push(next);
- lastTwo.shift();
- if (next >= n) break;
- total += next % 2 ? next : 0;
- }
- return total;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement