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
Selected Reading
Tribonacci series in JavaScript
The tribonacci sequence is a generalization of the Fibonacci sequence where each term is the sum of the three preceding terms. Unlike Fibonacci which uses two preceding terms, tribonacci uses three.
The standard tribonacci series starts with 0, 1, 1, and each subsequent term is the sum of the previous three terms:
0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149...
How It Works
Each term after the first three follows the formula:
T(n) = T(n-1) + T(n-2) + T(n-3)
Where T(0) = 0, T(1) = 1, T(2) = 1
Method 1: Using Recursion
const tribonacci = (n) => {
if (n === 0) return 0;
if (n === 1 || n === 2) return 1;
return tribonacci(n - 1) + tribonacci(n - 2) + tribonacci(n - 3);
};
// Generate first 10 terms
const generateTribonacci = (count) => {
const result = [];
for (let i = 0; i < count; i++) {
result.push(tribonacci(i));
}
return result;
};
console.log(generateTribonacci(10));
[ 0, 1, 1, 2, 4, 7, 13, 24, 44, 81 ]
Method 2: Using Iteration (More Efficient)
const tribonacciIterative = (count) => {
if (count <= 0) return [];
if (count === 1) return [0];
if (count === 2) return [0, 1];
const result = [0, 1, 1];
for (let i = 3; i < count; i++) {
const nextTerm = result[i-1] + result[i-2] + result[i-3];
result.push(nextTerm);
}
return result;
};
console.log(tribonacciIterative(12));
console.log("15th tribonacci number:", tribonacciIterative(16)[15]);
[ 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274 ] 15th tribonacci number: 1705
Method 3: Space-Optimized Approach
const tribonacciOptimized = (n) => {
if (n === 0) return 0;
if (n === 1 || n === 2) return 1;
let a = 0, b = 1, c = 1;
for (let i = 3; i <= n; i++) {
const temp = a + b + c;
a = b;
b = c;
c = temp;
}
return c;
};
// Generate series using optimized approach
for (let i = 0; i < 8; i++) {
console.log(`T(${i}) = ${tribonacciOptimized(i)}`);
}
T(0) = 0 T(1) = 1 T(2) = 1 T(3) = 2 T(4) = 4 T(5) = 7 T(6) = 13 T(7) = 24
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(3^n) | O(n) | Small values, educational |
| Iterative | O(n) | O(n) | Generating series |
| Space-Optimized | O(n) | O(1) | Single term calculation |
Conclusion
The tribonacci sequence extends Fibonacci by using three preceding terms. Use the iterative approach for generating series and the space-optimized method for calculating individual terms efficiently.
Advertisements
