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 nth element of the Padovan sequence using JavaScript
Padovan Sequence
The Padovan sequence is a sequence of integers P(n) defined by the initial values:
P(0) = P(1) = P(2) = 1
and the recurrence relation:
P(n) = P(n-2) + P(n-3)
The first few values of P(n) are:
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...
Problem
We need to write a JavaScript function that takes in a number n and returns the nth term of the Padovan sequence.
Using Iterative Approach
The most efficient approach uses iteration to calculate the sequence step by step:
const padovan = (num = 1) => {
// Handle base cases
if (num <= 2) return 1;
let secondPrev = 1, prev = 1, curr = 1, next = 1;
for (let i = 3; i <= num; i++) {
next = secondPrev + prev;
secondPrev = prev;
prev = curr;
curr = next;
}
return next;
};
// Test with different values
console.log("P(0) =", padovan(0));
console.log("P(5) =", padovan(5));
console.log("P(10) =", padovan(10));
console.log("P(15) =", padovan(15));
P(0) = 1 P(5) = 3 P(10) = 12 P(15) = 49
Using Recursive Approach
A simple recursive solution, though less efficient for large numbers:
const padovanRecursive = (n) => {
// Base cases
if (n <= 2) return 1;
// Recursive relation: P(n) = P(n-2) + P(n-3)
return padovanRecursive(n - 2) + padovanRecursive(n - 3);
};
console.log("Recursive P(8) =", padovanRecursive(8));
console.log("Recursive P(12) =", padovanRecursive(12));
Recursive P(8) = 7 Recursive P(12) = 21
Generating Multiple Terms
Function to generate the first n terms of the Padovan sequence:
const generatePadovanSequence = (count) => {
if (count <= 0) return [];
if (count === 1) return [1];
if (count === 2) return [1, 1];
if (count === 3) return [1, 1, 1];
let sequence = [1, 1, 1];
for (let i = 3; i < count; i++) {
let next = sequence[i - 2] + sequence[i - 3];
sequence.push(next);
}
return sequence;
};
console.log("First 10 terms:", generatePadovanSequence(10));
First 10 terms: [1, 1, 1, 2, 2, 3, 4, 5, 7, 9]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Iterative | O(n) | O(1) | Large values of n |
| Recursive | O(??) | O(n) | Small values, educational |
Conclusion
The iterative approach is most efficient for finding the nth Padovan number with O(n) time and O(1) space complexity. The recursive method is simpler to understand but becomes slow for larger values due to exponential time complexity.
