Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. // ES6 version separating out the generation of the fibonacci sequence
  2.  
  3. function * fibGen() {
  4. yield 1;
  5. yield 1;
  6.  
  7. const lastTwo = [1, 1];
  8.  
  9. while (true) {
  10. const next = lastTwo[0] + lastTwo[1];
  11. lastTwo.push(next);
  12. lastTwo.shift();
  13.  
  14. yield next;
  15. }
  16. }
  17.  
  18.  
  19. function sumOddFib(n) {
  20. let total = 0;
  21.  
  22. for (const fib of fibGen()) {
  23. if (fib >= n) break;
  24. total += fib % 2 ? fib : 0;
  25. }
  26.  
  27. return total;
  28. }
  29.  
  30.  
  31. // ES5 version
  32.  
  33. function sumOddFibV2(n) {
  34. if (n === 1) return 1;
  35. if (n === 2) return 2;
  36.  
  37. var total = 2;
  38. var lastTwo = [1, 1];
  39.  
  40. while (true) {
  41. var next = lastTwo[0] + lastTwo[1];
  42. lastTwo.push(next);
  43. lastTwo.shift();
  44.  
  45. if (next >= n) break;
  46.  
  47. total += next % 2 ? next : 0;
  48. }
  49.  
  50. return total;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement