Sha256: fe421ad5c6bcf2e270ee9340a9bdd96842d08fbf88efc731a1de3e8247a87ae2

Contents?: true

Size: 662 Bytes

Versions: 69

Compression:

Stored size: 662 Bytes

Contents

defmodule Prime do
  @doc """
  Generates the nth prime.
  """
  @spec nth(non_neg_integer) :: non_neg_integer
  def nth(count) do
    if count < 1, do: raise(ArgumentError)
    nth(count, 1000)
  end

  defp nth(count, max) do
    primes = primes_to(max)

    cond do
      Enum.count(primes) < count -> nth(count, max * 4)
      true -> Enum.at(primes, count - 1)
    end
  end

  defp primes_to(limit) do
    Enum.reduce(2..limit, [], fn number, primes ->
      if is_prime?(number, primes), do: [number | primes], else: primes
    end)
    |> Enum.reverse()
  end

  defp is_prime?(number, primes) do
    Enum.all?(primes, &(rem(number, &1) != 0))
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/nth-prime/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/nth-prime/example.exs