Created
September 13, 2012 15:37
-
-
Save nxvipin/3715155 to your computer and use it in GitHub Desktop.
Naive Parallel Factorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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