Finding value of a sequence for numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

Consider the following sequence sum −

$$seq(n,\:p)=\displaystyle\sum\limits_{k=0} \square(-1)^{k}\times\:p\:\times 4^{n-k}\:\times(\frac{2n-k}{k})$$

We are required to write a JavaScript function that takes in the numbers n and p returns the value of seq(n, p).

Example

Following is the code −

 Live Demo

const n = 12;
const p = 70;
const findSeqSum = (n, p) => {
   let sum = 0;
   for(let k = 0; k <= n; k++){
      const power = k % 2 === 0 ? 1 : -1;
      const fourPower = Math.pow(4, (n - k));
      const multiplier = ((2 * n) - k) / (k || 1);
      const term = (power * p * fourPower * multiplier);
      sum += term;
   };
   return sum;
};
console.log(findSeqSum(n, p));

Output

Following is the console output −

22131141616.42424
raja
Published on 20-Apr-2021 07:31:51
Advertisements