[erlang-questions] learning Erlang: factoring primes
Fri May 4 18:33:48 CEST 2007
I had trouble following that code; next_factor/1 doesn't have a simple
cohesive specification, it's more like just a label of a program point
in a loop. Here's how I would write it. (My Erlang experience is
% Return a list of the prime factors of N in arbitrary order.
factor(N) when is_integer(N), 1 < N ->
factor(N, 2, ).
% Return FD ++ Factors, where FD is the prime factors of N >= the test
% divisor D.
factor(N, D, Factors) ->
N < D*D -> [N|Factors];
0 =:= N rem D -> factor(N div D, D, [D|Factors]);
true -> factor(N, D + 1, Factors)
> From: "Martin Ankerl" <martin.ankerl@REDACTED>
> Hello everybody, I have just started learning Erlang and wrote one of
> my first programs. It is a very simple prime factoring program, but it
> works. I would appreciate comments about the programming style, is
> this how Erlang code should be written? Any way to make it simpler?
> Here is the code:
> % c('factor').
> % factor:fact(123456723456789).
> fact(1) ->
> fact(N) ->
> % io:format("~w\n", [N]),
> M = next_factor(N, 2, N rem 2),
> [ M | fact(N div M) ].
> % find the next factor
> next_factor(_, M, 0) ->
> next_factor(N, N, _) ->
> next_factor(N, M, _) ->
> next_factor(N, M+1, N rem (M+1)).
> Martin Ankerl | http://martin.ankerl.com
More information about the erlang-questions