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
Nth element of the Fibonacci series JavaScript
In this article, we'll learn how to find the nth element in the Fibonacci series using JavaScript. The Fibonacci sequence is a mathematical series where each number is the sum of the two preceding numbers.
What is the Fibonacci Series?
The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers. The series begins as:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...
For example, the 6th number in the series is 8, and the 10th number is 55.
Using Recursive Approach
The recursive method directly implements the mathematical definition of Fibonacci numbers. If n is less than 2, we return n itself (base cases). Otherwise, we return the sum of the (n-1)th and (n-2)th Fibonacci numbers.
// Recursive function to find nth Fibonacci number
function fibonacci(n) {
if (n < 2) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
// Test the function
console.log("6th Fibonacci number:", fibonacci(6));
console.log("10th Fibonacci number:", fibonacci(10));
console.log("0th Fibonacci number:", fibonacci(0));
console.log("1st Fibonacci number:", fibonacci(1));
6th Fibonacci number: 8 10th Fibonacci number: 55 0th Fibonacci number: 0 1st Fibonacci number: 1
Using Iterative Approach (More Efficient)
The recursive approach has exponential time complexity. For better performance with larger numbers, we can use an iterative approach:
// Iterative function to find nth Fibonacci number
function fibonacciIterative(n) {
if (n < 2) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
let temp = a + b;
a = b;
b = temp;
}
return b;
}
// Test the iterative function
console.log("15th Fibonacci (iterative):", fibonacciIterative(15));
console.log("20th Fibonacci (iterative):", fibonacciIterative(20));
15th Fibonacci (iterative): 610 20th Fibonacci (iterative): 6765
Performance Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(2^n) | O(n) | Small values, educational purposes |
| Iterative | O(n) | O(1) | Large values, production code |
Algorithm Steps
Recursive Approach:
Step 1 ? Check if n is less than 2. If yes, return n (base case).
Step 2 ? Otherwise, recursively call fibonacci(n-1) + fibonacci(n-2).
Step 3 ? Return the sum as the result.
Conclusion
Both recursive and iterative approaches can find the nth Fibonacci number. While recursion is intuitive and matches the mathematical definition, the iterative approach is more efficient for larger values due to its linear time complexity.
