Last active
February 12, 2016 13:52
-
-
Save vysakh0/24d28575e5409febedec to your computer and use it in GitHub Desktop.
Find the list of prime numbers upto n
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 | |
def run(number) do | |
max = :math.sqrt(number) |> round | |
result = Enum.to_list(2..number) | |
run(max, result, {result, []}) | |
end | |
def run(0, _, {res, sieve}) do | |
Enum.reverse(sieve) ++ res | |
end | |
def run(max, [ head | _ ], {result, sieve}) do | |
res = Enum.filter(result, fn(x) -> | |
rem(x, head) > 0 | |
end) | |
run(max - 1, res, {res, [ head | sieve ] } ) | |
end | |
end |
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 PrimeTest do | |
use ExUnit.Case | |
test "prime number" do | |
assert Prime.run(59) === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment