Created
September 7, 2015 17:28
-
-
Save wende/51600fab1f7a1d1bfbd1 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
def is_prime(x), do: (2..x |> Enum.filter(fn a -> rem(x, a) == 0) |> length()) == 1 | |
def prime(n), do: Stream.interval(1) |> Stream.drop(2) |> Stream.filter(&is_prime/1) |> Enum.take(n) |
Found another way of doing it, where we can avoid iterating the range as soon as we detect a non-prime number using Enum.any?/2
:
def is_prime(2), do: true
def is_prime(number) do
not Enum.any?(2..number-1, fn x -> rem(number, x) == 0 end)
end
def prime(n) do
Stream.interval(1)
|> Stream.filter(&is_prime/1)
|> Enum.take(n)
end
As @cbliard said. Thanks for your blog post.
The scala solution is 🥇
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Missing
end
in first line. Should bedef is_prime(x), do: (2..x |> Enum.filter(fn a -> rem(x, a) == 0 end) |> length()) == 1
Thanks for the original blog post 👍