Solving series 1,3,6,10 using recursion

Saurabh Staff asked 1 year ago

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

1 Answers
Best Answer
Saurabh Staff answered 1 year ago

Really simple JS solution:-

(function() {
print_series(1, 2, 10); // pass 3 params, viz, first num, diff between first 2 nums and num of entries we want in the series to be printed
})();
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) // base condition to break the recursive loop
return curr_num;
console.log(first_num); // print series
return print_series(curr_num + first_diff, first_diff + 1, num_elements - 1);
}

 

Codepen here