Generating Primes and the O'Neill paper, my final version, critique welcome
Angel Alvarez
clist@REDACTED
Thu Dec 17 13:26:49 CET 2009
Hi
This a my final version on erlang for the O'Neill paper and the message from
James Aimonetti.
Ive include synchronous calls between workers to avoid filling up mailboxes.
code is very barebones to keep it simple if anyone wants to see how it works :-P
I hope James will find it interesting and iwll be much pleased to ear any advices
from the gurus on this code.
/Angel
--
No imprima este correo si no es necesario. El medio ambiente está en nuestras manos.
__________________________________________
Clist UAH a.k.a Angel
__________________________________________
Money is a good standard. Micro$oft.
-------------- next part --------------
% "Genuine" Erathostenes sieve in erlang
% based on http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
% 2009 Angel Alvarez
%
% Process 1 2 3 4 5 6 7 ....
%
% 02 03 05 07 11 13 17
% P 02 -> 04
% P 03 04 -> 09
% C 04 == 04 09
% P 05 06 09 -> 25
% C 06 == 06 09 25
% P 07 08 09 25 -> 49
% C 08 == 08 09 25 49
% C 09 10 == 09 25 49
% C 10 == 10 12 25 49
% P 11 12 12 25 49 -> 121
% C 12 == 12 12 25 49 121
% P 13 14 15 25 49 121 -> 169
% C 14 == 14 15 25 49 121 169
% C 15 16 == 15 25 49 121 169
% C 16 == 16 18 25 49 121 169
% P 17 18 18 25 49 121 169 -> 289
-module(multi_erathostenes).
-author("angel@REDACTED").
-compile(export_all).
compare(X,Y) when X > Y -> greater;
compare(X,Y) when X < Y -> smaller;
compare(_,_) -> equal.
worker(Prime,UpperBound)->
receive
{test,Number,ParentPID} ->
ParentPID ! ok,
case compare(Number,UpperBound) of
equal ->
% io:format("[Worker of prime: ~w (~w)] Found composite: ~w~n",[Prime,UpperBound,Number]),
worker(Prime,UpperBound + Prime);
smaller ->
io:format("[Worker of prime: ~w (~w)] Spawn new worker for Prime: ~w~n",[Prime,UpperBound,Number]),
NextPID =spawn(?MODULE,worker,[Number,Number*Number]),
worker(Prime,UpperBound,NextPID)
end;
stop ->
noop
end.
worker(Prime,UpperBound,NextPID) ->
receive
{test,Number,ParentPID} ->
ParentPID ! ok,
case compare(Number,UpperBound) of
equal ->
% io:format("[Worker of prime: ~w (~w)] Found composite: ~w~n",[Prime,UpperBound,Number]),
worker(Prime,UpperBound + Prime,NextPID);
smaller ->
% io:format("[Worker of prime: ~w (~w)] passing along: ~w~n",[Prime,UpperBound,Number]),
NextPID ! {test,Number,self()},
receive
ok -> ok
end,
worker(Prime,UpperBound,NextPID);
greater ->
% io:format("[Worker of prime: ~w (~w)] passing along: ~w~n",[Prime,UpperBound,Number]),
NextPID ! {test,Number,self()},
receive
ok -> ok
end,
worker(Prime,UpperBound+Prime,NextPID)
end;
stop ->
NextPID ! stop,
noop
end.
start(N) ->
OnePID=spawn(?MODULE,worker,[2,4]),
cicle(3,N,OnePID).
cicle(Last,Last,Worker) ->
Worker ! stop;
cicle(Current,Last,Worker) ->
Worker ! {test,Current,self()},
receive
ok -> ok
end,
cicle(Current+1,Last,Worker).
More information about the erlang-questions
mailing list