[erlang-questions] Preventing Recursion from Crashing Me...

Alpár Jüttner <>
Sun Feb 24 12:01:35 CET 2008


The problem is that you use non-tail recursion in your factorial
implementation. Try this instead:

-module(math1).
-export([factorial/1]).

factorial(0) -> 1;
factorial(N) ->
    factorial(1,N).
factorial(P,1) ->
    P;
factorial(P,N) ->
    factorial(P*N,N-1).

This will not exhaust the system memory. Still do not expect a result
for factorial(1000000). First, it would take a very long time to compute
it (multiplication of such a big numbers are very slow). Secondly, after
a lot of computation you will get this:

% X=math1:factorial(1000000),0.
** exception error: a system limit has been reached
     in function  math1:factorial/2

My guess is that factorial(1000000) is just too big to store even as a
bignum. At least you can compute factorial(100000) using the
tail-recursive implementation.

Regards,
Alpar


On Sun, 2008-02-24 at 10:03 +1030, David Lloyd wrote:
> I rather quickly discovered that:
> 
> -module(math1).
> -export([factorial/1]).
> 
> factorial(0) -> 1;
> factorial(N) -> N * factorial(N-1).
> 
> 
> ...
> 
> erl
> % c(math1).
> % math1:factorial(1000000).
> 
> ...was able to take sufficient resources that I only just managed to 
> send a ctrl+alt+break (I'm running Gnome/JDS on Solaris SXCE b72 on a 
> Intel Quad Core E6600 with 4Gb of memory).
> 
> Apart from not using naive fibonacci ( :P ) is there a way to prevent 
> erlang from running away with such processes?
> 
> DSL
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list