Skip to content

Instantly share code, notes, and snippets.

@thebugcatcher
thebugcatcher / n_primes.ex
Last active February 1, 2021 09:48
Find if a number is prime in elixir and get a list of primes.
# Given an input, this program returns a list of all primes numbers less than the input.
defmodule NPrimes do
def get_primes(n) when n < 2, do: []
def get_primes(n), do: Enum.filter(2..n, &is_prime?(&1))
defp is_prime?(n) when n in [2, 3], do: true
defp is_prime?(x) do
start_lim = div(x, 2)
Enum.reduce(2..start_lim, {true, start_lim}, fn(fac, {is_prime, upper_limit}) ->