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
Finding the nth element of the lucas number sequence in JavaScript
Lucas numbers are a sequence similar to Fibonacci numbers but with different starting values. They follow a specific mathematical pattern where each number is the sum of the two preceding ones.
Lucas Number Sequence Definition
The Lucas sequence is defined as:
L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) for n ? 2
The sequence starts: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123...
Problem Statement
We need to write a JavaScript function that takes a number n and returns the nth Lucas number from the sequence.
Using Recursive Approach
The most straightforward approach uses recursion to implement the mathematical definition:
const lucas = (num = 1) => {
if (num === 0)
return 2;
if (num === 1)
return 1;
return lucas(num - 1) + lucas(num - 2);
};
const num = 21;
console.log(`Lucas number at position ${num}: ${lucas(num)}`);
// Let's also show first few Lucas numbers
console.log("First 10 Lucas numbers:");
for (let i = 0; i < 10; i++) {
console.log(`L(${i}) = ${lucas(i)}`);
}
Lucas number at position 21: 24476 First 10 Lucas numbers: L(0) = 2 L(1) = 1 L(2) = 3 L(3) = 4 L(4) = 7 L(5) = 11 L(6) = 18 L(7) = 29 L(8) = 47 L(9) = 76
Optimized Iterative Approach
For larger values of n, recursion becomes inefficient due to repeated calculations. An iterative approach is more performant:
const lucasIterative = (n) => {
if (n === 0) return 2;
if (n === 1) return 1;
let prev2 = 2; // L(0)
let prev1 = 1; // L(1)
let current;
for (let i = 2; i <= n; i++) {
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return current;
};
console.log(`Lucas(21) using iterative: ${lucasIterative(21)}`);
console.log(`Lucas(30) using iterative: ${lucasIterative(30)}`);
Lucas(21) using iterative: 24476 Lucas(30) using iterative: 1346269
Comparison of Approaches
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(2^n) | O(n) | Small values, educational purposes |
| Iterative | O(n) | O(1) | Larger values, production code |
Key Properties of Lucas Numbers
Lucas numbers have interesting mathematical properties. They're closely related to Fibonacci numbers and the golden ratio, making them useful in various mathematical applications and algorithms.
Conclusion
The recursive approach directly implements the mathematical definition but becomes inefficient for large n. The iterative method is preferred for production code due to its linear time complexity and constant space usage.
