[erlang-questions] learning Erlang: factoring primes

Darius Bacon darius@REDACTED
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
limited, too.)

-module(factor).
-export([factor/1]).

% 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) ->
    if
        N < D*D       -> [N|Factors];
        0 =:= N rem D -> factor(N div D, D, [D|Factors]);
        true          -> factor(N, D + 1, Factors)
    end.

> 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:
> 
> -module(factor).
> -export([fact/1]).
> 
> % 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) ->
>         M;
> next_factor(N, 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 mailing list