[erlang-questions] learning Erlang: factoring primes
Matthias Lang
matthias@REDACTED
Fri May 4 09:50:43 CEST 2007
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
>
More information about the erlang-questions
mailing list