Open In App

Nth Tribonacci Number using JavaScript

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:

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).

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.

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

Article Tags :