Open In App

JavaScript Program for Solving f(n)= (1) + (2*3) + (4*5*6) … n using Recursion

In this article, we will learn how we can solve the sum of a series that follows a specific pattern. In this problem, we will explore the process of determining the sum of the series mentioned below. Upon examination of the pattern presented it becomes evident that each term, in the series is obtained by multiplying numbers together.

Example:



Input : 3
Output: 127
Series: (1) + (2*3) + (4*5*6)
Input : 5
Output: 365527
Series: (1) + (2*3) + (4*5*6) + (7*8*9*10) + (11*12*13*14*15)

Recursive Approach

Example: This example shows the use of the above-explained approach.




// SeriesSum Function
function seriesSum(start, current, N) {
    let product = 1;
  
    if (current > N) {
        return 0;
    }
  
    for (let i = start; i < start + current; i++) {
        product *= i;
    }
  
    return product + seriesSum(
        start + current, current + 1, N);
}
  
// Driver code
let N = 5;
let result = seriesSum(1, 1, N);
console.log(result);

Output

365527

Time Complexity: O(n2), because of n recursive calls.

Space Complexity: O(n), beacuse function uses an array of size n.

Article Tags :