Skip to content

Instantly share code, notes, and snippets.

@manewitz
Last active February 16, 2023 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manewitz/f65d8404d5e1a95dfa77274c8f705cc9 to your computer and use it in GitHub Desktop.
Save manewitz/f65d8404d5e1a95dfa77274c8f705cc9 to your computer and use it in GitHub Desktop.
Elixir implementation of the Sieve of Eratosthenes algorithm for finding prime numbers.
defmodule SieveOfEratosthenes do
@doc """
https://www.baeldung.com/cs/prime-number-algorithms
Naive implementation of the Sieve Of Eratosthenes for finding primes below `number`
"""
@spec primes(number) :: list
def primes(1), do: []
def primes(n) do
numbers =
cond do
n <= 3 -> Enum.to_list(2..n)
true -> Enum.to_list(2..trunc(:math.sqrt(n)))
end
sieve(numbers, [])
|> Enum.reverse()
end
defp sieve([], primes), do: primes
defp sieve([p | rest], primes) do
primes = [p | primes]
sieve(for(n <- rest, rem(n, p) != 0, do: n), primes)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment