Tribonacci series in JavaScript


Tribonacci Series:

The tribonacci sequence is a generalization of the Fibonacci sequence where each term is the sum of the three preceding terms.

For example, the first few terms of the tribonacci series are −

0,1,1,2,4,7,13,24,44,81,149

We are required to write a JavaScript function that takes in a number, say num, as the only argument.

The function should then return an array of num elements, containing the first num terms of the tribonacci series.

For example:

f(6) = 0,

Example

Following is the code:

const tribonacci = (num = 1) => {
   if (num === 0 || num === 1 || num === 2){
      return 0;
   };
   if (num == 3){
      return 1;
   }else{
      return tribonacci(num - 1) +
      tribonacci(num - 2) +
      tribonacci(num - 3);
   }
}
const trib = num => {
   const res = [];
   for (let i = 1; i <= num; i++){
      res.push(tribonacci(i));
   };
   return res
};
console.log(trib(15));

Output

Following is the console output −

[ 2, 1, 4, 3, 6, 5 ]

Updated on: 18-Jan-2021

867 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements