Finding nth element of the Padovan sequence using JavaScript

JavascriptWeb DevelopmentFront End Technology

Padovan Sequence

The Padovan sequence is the sequence of integers P(n) defined by the initial values −

P(0) = P(1) = P(2) = 1

and the recurrence relation,

P(n) = P(n-2) + P(n-3)

The first few values of P(n) are

1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, …

Problem

We are required to write a JavaScript function that takes in a number n and return the nth term of the Padovan sequence.

Example

Following is the code −

 Live Demo

const num = 32;
const padovan = (num = 1) => {
   let secondPrev = 1, pPrev = 1, pCurr = 1, pNext = 1;
   for (let i = 3; i <= num; i++){
      pNext = secondPrev + pPrev;
      secondPrev = pPrev;
      pPrev = pCurr;
      pCurr = pNext;
   };
   return pNext;
};
console.log(padovan(num));

Output

5842
raja
Published on 19-Apr-2021 15:14:59
Advertisements