Skip to content

Instantly share code, notes, and snippets.

@nxvipin
Created September 13, 2012 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nxvipin/3715155 to your computer and use it in GitHub Desktop.
Save nxvipin/3715155 to your computer and use it in GitHub Desktop.
Naive Parallel Factorial
% Naive Parallel Factorial
% The second line defines the number of processes that will be spawned.
% Modify the number to control the task distribution.
-module(factorial).
-define(PROC, 4).
-export([sub_factorial/2, sub_factorial/3]).
-export([calculate/1, calculate/2]).
sub_factorial(V, N, PID) ->
PID ! sub_factorial(V, N).
sub_factorial(V, N) when V =< N ->
V*sub_factorial(V+?PROC,N);
sub_factorial(V, N) when V > N ->
1.
calculate(N) ->
PID = spawn(factorial,calculate,[?PROC, []]),
Range = lists:seq(1,?PROC),
[spawn(factorial,sub_factorial,[X, N, PID]) || X <- Range].
calculate(0, F) ->
io:format("Calculating product ~n"),
X = lists:foldl(fun(X,Prod) -> X*Prod end, 1, F),
io:format("Fact Answer : ~p ~n",[X]),
1;
calculate(C, F) ->
receive
X -> calculate(C-1, [X|F])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment