Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript code for recursive Fibonacci series
We have to write a recursive function fibonacci() that takes in a number n and returns an array with first n elements of fibonacci series. The Fibonacci sequence starts with 0 and 1, where each subsequent number is the sum of the two preceding ones.
Understanding the Fibonacci Sequence
The Fibonacci sequence follows this pattern: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... where F(n) = F(n-1) + F(n-2).
Recursive Implementation
Here's a recursive approach that builds the Fibonacci array:
const fibonacci = (n, res = [], count = 1, last = 0) => {
if(n){
return fibonacci(n-1, res.concat(count), count+last, count);
};
return res;
};
console.log(fibonacci(8));
console.log(fibonacci(0));
console.log(fibonacci(1));
console.log(fibonacci(10));
[ 1, 1, 2, 3, 5, 8, 13, 21 ] [] [ 1 ] [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]
How It Works
The function uses four parameters:
- n: Number of elements remaining to generate
- res: Result array (starts empty)
- count: Current Fibonacci number (starts at 1)
- last: Previous Fibonacci number (starts at 0)
Alternative Simple Recursive Approach
Here's a more traditional recursive Fibonacci implementation:
function fibonacciSimple(n) {
if (n <= 1) return n;
return fibonacciSimple(n - 1) + fibonacciSimple(n - 2);
}
// Generate array of first n Fibonacci numbers
function fibonacciArray(n) {
const result = [];
for (let i = 0; i < n; i++) {
result.push(fibonacciSimple(i));
}
return result;
}
console.log(fibonacciArray(8));
console.log(fibonacciArray(5));
[ 0, 1, 1, 2, 3, 5, 8, 13 ] [ 0, 1, 1, 2, 3 ]
Comparison
| Approach | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Tail Recursive (first example) | O(n) | O(n) | Complex |
| Simple Recursive | O(2^n) | O(n) | Simple |
Conclusion
The tail recursive approach is more efficient for generating Fibonacci arrays, while the simple recursive method is easier to understand but has exponential time complexity for large inputs.
