0

The below function is exceeding the maximum call stack when running on node.js v8.5 on OS X 10.13 (High Sierra)

"use strict";

function sum_multiples(i, max, sum){
    if(i >= max) return sum;
    return ((i%3 === 0) || (i%5 === 0)) ? sum_multiples(i+1, max, sum+i) : sum_multiples(i+1, max, sum);
}

console.log(sum_multiples(1, 1000, 0));

Should this be structured differently to avoid exceeding the call stack or is the problem the engine being used?

Using a while or for loop doesn't cause this problem and the machine that this is running on can compute the solution for this for 1,000,000,000,000 using those methods.

wfaye
  • 268
  • 1
  • 2
  • 10
  • Not sure if this is still accurate at this time, but some relevant reading certainly https://stackoverflow.com/questions/23260390/node-js-tail-call-optimization-possible-or-not?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – CollinD May 31 '18 at 14:29
  • 1
    This [table](https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)) does not list tail call optimization as supported feature of node `>=8 < 9` – t.niese May 31 '18 at 14:31
  • maybe this helps : http://www.thinkingincrowd.me/2016/06/06/How-to-avoid-Stack-overflow-error-on-recursive/ – Taki May 31 '18 at 14:37
  • tail call recursion is a feature of ES, however it is not really supported yet. I think that your recursive call is in tail call position, so it might work in the future. – Jonas Wilms May 31 '18 at 15:00
  • I think the duplicate collin mentioned provides the current state of the art, if soneone disagrees, i will be glad to reopen – Jonas Wilms May 31 '18 at 15:04

0 Answers0