Last active
May 18, 2017 05:05
-
-
Save tamanugi/ae624d3615fbeae37efdeb59d7c76b8c to your computer and use it in GitHub Desktop.
Elixirでエラトステネスの篩を実装してみた ref: http://qiita.com/tamanugi/items/8b97e93f94fdb014100b
This file contains 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 Erastosthenes do | |
def sieve(prime, next, last?) do | |
receive do | |
n when rem(n, prime) == 0 -> | |
sieve(prime, next, last?) | |
n -> | |
send next, n | |
next = if last? do | |
# 自身が最後の篩だったら次の篩を生成する | |
{pid, _} = spawn_monitor Erastosthenes, :sieve, [n, next, true] | |
pid | |
else | |
next | |
end | |
sieve(prime, next, false) | |
end | |
end | |
def output do | |
receive do | |
n -> | |
IO.puts "#{n} is prime." | |
output() | |
end | |
end | |
end | |
opid = spawn Erastosthenes, :output, [] | |
{spid, _} = spawn_monitor Erastosthenes, :sieve, [2, opid, true] | |
2..100 | |
|> Stream.map(&(send spid, &1)) | |
|> Enum.to_list |
This file contains 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
$ iex | |
iex(1)> c"erastosthenes.exs" | |
3 is prime. | |
5 is prime. | |
7 is prime. | |
11 is prime. | |
13 is prime. | |
17 is prime. | |
19 is prime. | |
23 is prime. | |
29 is prime. | |
31 is prime. | |
37 is prime. | |
41 is prime. | |
[Erastosthenes] | |
43 is prime. | |
47 is prime. | |
53 is prime. | |
59 is prime. | |
61 is prime. | |
67 is prime. | |
71 is prime. | |
73 is prime. | |
79 is prime. | |
83 is prime. | |
89 is prime. | |
97 is prime. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment