# [erlang-questions] learning Erlang: factoring primes

Ludovic Coquelle lcoquelle@REDACTED
Fri May 4 10:24:21 CEST 2007

```Not sure this is useful here, but fact could be made tail-recursive:
fact(N) ->
fact(N, []).
fact(1, Factors) ->
Factors;
fact(N,  Factors) ->
M = next_factor(N, 2), % using definition of Matthias
fact(N div M, [M|Factors]).
(haven't tested this code ...)

On 5/4/07, Matthias Lang <matthias@REDACTED> wrote:
>
>
> The programming style is fine. I only see trivial things which are
> hardly worth mentioning:
>
>   - You don't need to quote atoms like 'factor' (in your compile comment)
>   - The program currently hangs for negative numbers
>
> It can be simplified a bit, though it's already pretty good. You can
> rewrite next_factor in two clauses like this:
>
>   first_factor(N, M) when N rem M == 0 ->
>     M;
>   first_factor(N, M) ->
>     first_factor(N, M+1).
>
> Matthias
>
>
> Martin Ankerl writes:
> > 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
> > _______________________________________________
> > erlang-questions mailing list
> > erlang-questions@REDACTED
> > http://www.erlang.org/mailman/listinfo/erlang-questions
> >
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20070504/7231938a/attachment.htm>
```