Advertisement
YavorJS

2. Fibonacci

Jul 4th, 2017
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. //solution 1:
  2.  
  3. function main(n) {
  4. let arr = [1, 1];
  5.  
  6. for (let i = 2; i < n; i++) {
  7. let next = arr[i - 1] + arr[i - 2];
  8. console.log(arr[i - 1]);
  9. arr.push(next);
  10. }
  11.  
  12. if (n === 1) arr = [1];
  13.  
  14. return arr;
  15. }
  16.  
  17. console.log(main(1));
  18.  
  19. //solution: 2:
  20.  
  21. function solution(n) {
  22. let solve = (function main() {
  23. let f1 = 0;
  24. let f2 = 1;
  25.  
  26. return function () {
  27. let f3 = f1 + f2;
  28. [f1, f2] = [f2, f3];
  29. return f1;
  30. }
  31. })();
  32. let arr = [];
  33. for (let i = 0; i < n; i++) {
  34. let result = solve();
  35. arr.push(result);
  36. }
  37. return arr;
  38. }
  39.  
  40. console.log(solution(6));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement