Anurag Jain - 1 year ago 66

Javascript Question

I have a recurrence series so i have converted into recursion form.

But it will show as maximum stack size reached.

The same code is **working with n=4** as fn(4) and working correctly but not working with higher values. what is the problem with higher values such as n = Math.pow(10, 18)

`var fn = function(n){`

// take initial value of f(0) = 1 & f(1) = 1

if(n===1 || n=== 0) return 1;

//calculate on basis of initial values

else if (n === -1) return (fn(1) - 3* fn(0) - gn(-1) - 2* gn(0));

else

return (3*fn(n-1) + 2 * fn(n-2) + 2* gn(n-1) + 3* gn(n-2));

};

var gn = function(n){

// take initial value of g(0) = 1 & g(1) = 1

if (n === 1 || n === 0) return 1;

//calculate on basis of initial values

else if(n === -1) return ((gn(1) - gn(0)) / 2);

else return (gn(n-1) + 2* gn(n-2));

};

Answer

The problem with higher values, such as `n = Math.pow(10, 18)`

is that the stack is simply not that big. (Not even close.) You can usually have a stack depth of a couple thousand, and not much more.

You should use iteration instead.

Source (Stackoverflow)