Created
January 25, 2018 15:01
-
-
Save brunoczim/75e51c25eb850e97edbba484987c5b0c to your computer and use it in GitHub Desktop.
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
defmodule Paramath do | |
def fast_fac(n, procn, pid) do | |
recver = spawn_link(fn -> recv(procn, 1, pid) end) | |
mkfac(n, div(n, procn) + rem(n, procn), recver) | |
end | |
defp mkfac(n, intval, out) do | |
cond do | |
n > intval -> | |
spawn_link(fn -> calc_range(n, n - intval, 1, out) end) | |
mkfac(n - intval, intval, out) | |
n > 1 -> | |
spawn_link(fn -> calc_range(n, 1, 1, out) end) | |
{} | |
:true -> {} | |
end | |
end | |
defp calc_range(from, downto, res, out) do | |
if from > downto do | |
calc_range(from - 1, downto, res * from, out) | |
else | |
send(out, {:partial, res}) | |
end | |
end | |
defp recv(i, res, out) do | |
if i > 0 do | |
receive do | |
{:partial, n} -> recv(i - 1, res * n, out) | |
end | |
else | |
send(out, {:factorial, res}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment