Open In App

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

Last Updated : 19 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • The idea includes a function called ‘seriesSum’ that uses recursion to find the sum of products in a series of numbers.
  • First, the function checks if the current position goes beyond the limit N. In that case, it returns 0.
  • If not it multiplies the numbers from start to start + current. 1. Adds them up as a result.
  • Next, the function calls itself recursively with updated values, for start, current, and N. This helps in calculating the sum of products.
  • This process continues until the current position exceeds N. Finally, the accumulated sum of products is returned and displayed on the console.

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

Javascript




// 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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads