Fibonacci series in JavaScript | Four different ways
Fibonacci series in javascript with Four different ways
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..
The next number is found by adding up the two numbers before it:
- the 3 is found by adding the two numbers before it (1+2),
- the 5 is found by adding the two numbers before it (2+3),
- the 13 is (5+6),
- and so on!
The Rule is series[n] = series[n−1] + series[n−2]
Let’s do the coding…
💡Print Fibonacci Series by Using simple For Loop
function printFib(n) { const series = [0, 1]; for (let i = 2; i <= n; i++) { series.push(series[i - 2] + series[i - 1]) } console.log(series) } printFib(6) // (6) [0, 1, 1, 2, 3, 5]
💡Print Fibonacci Series by Using While Loop
function printFibWithWhile(n) { const series = [0, 1]; let i = 2; while (i < n) { series.push(series[i - 2] + series[i - 1]) // series.push(series[series.length - 1] + series[series.length - 2]) i++; } console.log(series) } printFibWithWhile(10) // (10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
💡Print Fibonacci Series by Using recursion
function printFibWithRecursion(n) { const series = [0, 1]; function fib(n) { if (n === 2) { return; } series.push(series[series.length - 1] + series[series.length - 2]) fib(n - 1) } fib(n); console.log(series) return series; } printFibWithRecursion(10);
💡Print Fibonacci Series by Using ES6 Function Generator
function fibSeries(n) { function* fib() { var a = 0; var b = 1; var c = a; while (c < Number.POSITIVE_INFINITY) { yield c; a = b; b = c; c = a + b; } } const gen = fib(); const series = []; for (let i = 0; i <= n; i++) { series.push(gen.next().value) } console.log(series) } fibSeries(10)
💻 Time Complexity of All four ways is O(n)
Learn more on Function Generator and Yield in JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield
✔ Array Representation of Binary Tree | Full Tree & Complete Binary Tree
✔ Graphs in Data Structure, Types & Traversal with BFS and DFS, Algorithms
✔ Traversing 2 D array with BFS & DFS Algorithm in JavaScript
✔ JavaScript Rotate 2D matrix 90 degrees clockwise | Top Interview Question
✔ HashTable Data Structure in JavaScript with Add Delete & Search Algorithms
✔ Trie Data Structure – Insert Search Delete & Print Program with JavaScript
✔ Top JavaScript Commonly asked Algorithms in Interview
✔ JavaScript String Permutation Program with nice explanation
Fibonacci series in javascript