Fibonacci like sequence in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let us define a sequence using the following definition −

Given terms t1 and t2, the two consecutive terms of this sequence, then the third term of this sequence will equal to −

t3 = t1 + (t2 * t2)

Like the Fibonacci sequence, the first two terms of this sequence will always be 0 and 1 respectively.

We are required to write a JavaScript function that takes in a number, say n. The function should then compute and return the nth term of the sequence described above.

For example − If n = 6, then

t6 = 27

because the sequence is −

0 1 1 2 5 27

Example

The code for this will be −

const num = 6;
const findSequenceTerm = (num = 1) => {
   const arr = [0, 1];
   while(num > arr.length){
      const last = arr[arr.length − 1];
      const secondLast = arr[arr.length − 2];
      arr.push(secondLast + (last * last));
   };
   return arr[num − 1];
};
console.log(findSequenceTerm(num));

Output

And the output in the console will be −

27
raja
Updated on 23-Nov-2020 08:01:57

Advertisements