Solving series 1,3,6,10… using recursion

5.33K viewsProgramming
0

How would you solve 1,3,6 and 10 using the recursive and explicit formulas?

Changed status to publish
0

JavaScript code below. It uses, first number , difference between first 2 numbers and number of elements to print as inputs, to output the series.

// self executing function
(function() {
   print_series (1, 2, 10);      /* input params, first number, diff between first 
                                        2 elements and number of elements to print */
})();
     /* algorithm which prints the series recursively */
function print_series (first_num, first_diff, num_elements) {
   // prints series 1 3 6 10... recursively
   var curr_num = first_num;
   if (0 === num_elements)
        return curr_num;
    console.log(first_num);
    return print_series(curr_num + first_diff, first_diff + 1, num_elements - 1);
}

Answered question
Write your answer.

Categories