Skip to content

Instantly share code, notes, and snippets.

@wende
Created September 7, 2015 17:28
Show Gist options
  • Save wende/51600fab1f7a1d1bfbd1 to your computer and use it in GitHub Desktop.
Save wende/51600fab1f7a1d1bfbd1 to your computer and use it in GitHub Desktop.
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)
@cbliard
Copy link

cbliard commented Oct 5, 2018

Missing end in first line. Should be def is_prime(x), do: (2..x |> Enum.filter(fn a -> rem(x, a) == 0 end) |> length()) == 1

Thanks for the original blog post 👍

@xavvvier
Copy link

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