Skip to content

Instantly share code, notes, and snippets.

@brunoczim
Created January 25, 2018 15:01
Show Gist options
  • Save brunoczim/75e51c25eb850e97edbba484987c5b0c to your computer and use it in GitHub Desktop.
Save brunoczim/75e51c25eb850e97edbba484987c5b0c to your computer and use it in GitHub Desktop.
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