Skip to content

Instantly share code, notes, and snippets.

@iwan iwan/prime.ex

Created Jul 9, 2018
Embed
What would you like to do?
Primality test in Elixir - a simple method
defmodule Prime do
# https://en.wikipedia.org/wiki/Primality_test#Simple_methods
def is_prime(0) do
false
end
def is_prime(1) do
false
end
def is_prime(2) do
true
end
def is_prime(3) do
true
end
def is_prime(n) when rem(n,2)==0 do
false
end
def is_prime(n) when rem(n,3)==0 do
false
end
def is_prime(n) do
_is_prime(n, 5)
end
defp _is_prime(n, i) when i*i<=n do
if rem(n,i)==0 or rem(n,i+2)==0 do
false
else
_is_prime(n,i+1)
end
end
defp _is_prime(n, i) when i*i>n do
true
end
end
# Enum.filter(1..100, fn(x) -> Prime.is_prime(x) end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.