The Tribonacci sequence is similar to the Fibonacci sequence, where each term is the sum of the three preceding terms. We will explore various methods to efficiently compute the Nth Tribonacci number using JavaScript.
Problem Description: The task is to find the Nth Tribonacci number, denoted as T(n), where T(n) follows the recurrence relation:
T(0) = 0
T(1) = 1
T(2) = 1
T(n) = T(n-1) + T(n-2) + T(n-3) for n >= 3
There are several approaches to finding the Nth Tribonacci number using JavaScript which are as follows:
Table of Content
Recursive Approach
The recursive approach directly follows the definition of the Tribonacci sequence. We define a recursive function tribonacci
that computes T(n) based on the recurrence relation.
Example: To demonsrtate finding the Nth Tribonacci number using recurson in JavaScript.
function tribonacci(n)
{
if (n === 0) return 0;
else if (n === 1 || n === 2) return 1;
return tribonacci(n - 1)
+ tribonacci(n - 2)
+ tribonacci(n - 3);
}
console.log(tribonacci(5))
Output
7
Time Complexity: Exponential (O(3^n))
Space Complexity: O(n) due to the recursion stack
Iterative Approach
The iterative approach uses a bottom-up dynamic programming technique to compute the Tribonacci numbers from T(0) up to T(n).
- Check if n is 0: If n is 0, return 0. (Base case)
- Check if n is 1 or 2: If n is 1 or 2, return 1. (Base case)
- Initialize variables: Set a to 0, b to 1, and c to 1.
- Loop through the sequence: Start a loop from 3 to n.
- Calculate the next term: Sum a, b, and c to get the next term.
- Update variables: Shift a, b, and c to the next values.
- Return the nth term: After the loop, return the value of c.
Example: To demonsrtate finding the Nth tribonacci number using iteration in JavaScript.
function tribonacci(n) {
if (n === 0) return 0;
else if (n === 1 || n === 2) return 1;
let a = 0, b = 1, c = 1;
for (let i = 3; i <= n; i++) {
let next = a + b + c;
a = b;
b = c;
c = next;
}
return c;
}
console.log(tribonacci(5))
Output
7
Time Complexity: Linear (O(n))
Space Complexity: Constant (O(1))
Dynamic Programming (Memoization)
This approach uses dynamic programming with memoization to optimize the recursive solution.
- Base case: if n is 0 return 0, if n is either 1 or 2 return 1.
- For every other number(n), when if it is present in the dp map.
- if yes, return the value present in the map, else call the tibonacci function on the number.
- store the calaculate value in the dp map.
Example: To demonstrate finding the tribonacci number using dynamic programming in JavaScript.
dp = {};
function calculateTribonacci(n) {
if (n in dp) return dp[n];
if (n === 0) return 0;
else if (n === 1 || n === 2) return 1;
dp[n] = calculateTribonacci(n - 1)
+ calculateTribonacci(n - 2)
+ calculateTribonacci(n - 3);
return dp[n];
}
console.log(calculateTribonacci(5))
Output
7
Time Complexity: Linear (O(n))
Space Complexity: Linear (O(n)) due to memoization