Finding nth element of the Padovan sequence using JavaScript

JavascriptWeb DevelopmentFront End Technology

<h2>Padovan Sequence</h2><p>The Padovan sequence is the sequence of integers P(n) defined by the initial values &minus;</p><pre class="result notransalte">P(0) = P(1) = P(2) = 1</pre><p>and the recurrence relation,</p><pre class="result notransalte">P(n) = P(n-2) + P(n-3)</pre><p>The first few values of P(n) are</p><pre class="result notransalte">1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, &hellip;</pre><h2>Problem</h2><p>We are required to write a JavaScript function that takes in a number n and return the nth term of the Padovan sequence.</p><h2>Example</h2><p>Following is the code &minus;</p><p><a class="demo" href="http://tpcg.io/3h4qMytv" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notransalte">const num = 32; const padovan = (num = 1) =&gt; { &nbsp; &nbsp;let secondPrev = 1, pPrev = 1, pCurr = 1, pNext = 1; &nbsp; &nbsp;for (let i = 3; i &lt;= num; i++){ &nbsp; &nbsp; &nbsp; pNext = secondPrev + pPrev; &nbsp; &nbsp; &nbsp; secondPrev = pPrev; &nbsp; &nbsp; &nbsp; pPrev = pCurr; &nbsp; &nbsp; &nbsp; pCurr = pNext; &nbsp; &nbsp;}; &nbsp; &nbsp;return pNext; }; console.log(padovan(num));</pre><h2>Output</h2><pre class="result notransalte">5842</pre>
raja
Updated on 19-Apr-2021 11:48:27

Advertisements