+ 1

Factorial recursion gives 'too much recursion' error

I created a calculator that runs without using any javascript arithmetic operators, and as a result multiplication is just recursive addition. The factorial recursion method also uses this multiplication method. Is there any way I could change the factorial method to not give this error? The only thing I could think of is making the multiplication with for loops instead of recursion, but I would prefer to keep it recursive. https://code.sololearn.com/WcyB3sbZalbz/

18th Jun 2018, 6:16 PM
Bryce Parkman
Bryce Parkman - avatar
5 Respostas
+ 3
deep recursion usually leads to something called a stack overflow. when a function is called the return adress is stored on the stack. i assume it is similar with javascript
18th Jun 2018, 8:08 PM
Max
Max - avatar
+ 2
I added a loop to output all positive factorials up to 200! I'm unsure how the recursion issue gets a chance to arise [I did not duplicate it], because the fact() operation simply returns 0 between 17! and 200! (note on max integer below) 7: 5040 8: 40320 ... correct to here ... incorrect from here 9: 35200 (off by 327680) ... 16 = 32768 17 = 32768 18 = 0 ... 200 = 0 Note once fixed: any results above 78! will be corrupt if you use Javascript's built-in numbers or parseInt (79! exceeds MAX_SAFE_INT).
18th Jun 2018, 7:12 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Max - try adding an alert(fact(10000)). It just alerts 0. So...I'm curious where it's arising. Maybe I'm not doing it right by just calling the function directly like that :/
18th Jun 2018, 8:44 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
I think that the problem is that your code handle basic operation with 16-bit integer and this make problem on operations that overflow this limit (like factorial do for sure)... In practice you have to not limit your int representing with fixed 16-bit/chars but you have to make with variable length
18th Jun 2018, 10:13 PM
KrOW
KrOW - avatar
0
Kirk Schafer The error was only occasionally happening, when i inplemented it into the input bar i seemed to be getting the error the most. The part with the overflow error makes sense to me though i shouldve stated it happened when i put in numbers like 4 I will try again though.
18th Jun 2018, 9:00 PM
Bryce Parkman
Bryce Parkman - avatar