%% $Id: factorial.erl,v 1.5 2019/12/09 21:38:30 leavens Exp leavens $ -module(factorial). -export([fact/1,mult_server/0]). %% Author: Gene Sher and Gary T. Leavens % We start off by building a process that answers to the rpc call {factorial,Num}, % and then calculates the factorial. We then develop the concurrent function. % The algorithm is simple: we break the number into two parts, % and then calculate each part, and multiply the solutions together. -spec fact(non_neg_integer()) -> non_neg_integer(). fact(0) -> 1; fact(N) -> Me = self(), P1 = spawn(fun mult_server/0), P2 = spawn(fun mult_server/0), P1!{Me, N, N div 2 + 1}, P2!{Me, N div 2, 1}, receive V1 -> receive V2 -> V1 * V2 end end. -spec mult_server() -> none(). mult_server() -> receive {Pid,N,M} -> Pid ! multiply_down_to(N,M,1) end. -spec multiply_down_to(integer(),non_neg_integer(),non_neg_integer()) -> non_neg_integer(). multiply_down_to(N,M,Acc) -> case N < M of true -> Acc; false -> multiply_down_to(N-1,M,N*Acc) end.