Created
July 9, 2018 10:25
-
-
Save iwan/dfbcb7f537d73a6a8b145c512da6f4b1 to your computer and use it in GitHub Desktop.
Primality test in Elixir - a simple method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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