Skip to content

Instantly share code, notes, and snippets.

@lukaswilkeer
Last active September 8, 2020 02:09
Show Gist options
  • Save lukaswilkeer/ed277d3eb0cd27daa666cb08b2337225 to your computer and use it in GitHub Desktop.
Save lukaswilkeer/ed277d3eb0cd27daa666cb08b2337225 to your computer and use it in GitHub Desktop.
-module(primality).
-export([primality/1]).
%% @doc test the primality number using the Sieve of Eratosthenes.
-spec(primality(number()) -> boolean()).
primality(Nmbr) ->
List = lists:reverse(generate_integer_list(Nmbr, [Nmbr])),
Enumerated = enumarate(lists:last(List), [lists:nth(1, List)]),
Marked = lists:filter(fun(Elem) -> Elem =/= false end, Enumerated),
Number = lists:member(Marked, Nmbr),
Number.
%% @doc generate a list of integer betwenn 2 and Nmbr
-spec(generate_integer_list(number(), list()) -> list()).
generate_integer_list(Nmbr, List) ->
Last = lists:last(List),
Number = Nmbr-1,
if
Last > 2 -> generate_integer_list(Number, lists:append(List, [Number]));
Last == 2 -> List
end.
%% @doc generate a list of multiples of 2
-spec(enumarate(number(), list()) -> list()).
enumarate(Limit, List) ->
Last = lists:last(List),
Number = if
Last =/= false; Last rem 2 == 0 -> false;
Last =/= false; Last div 3 == 0 -> false;
Last -> Last
end,
NotFalseList = lists:filter(fun(Elem) -> Elem =/= false end, List),
NotFalse = lists:last(NotFalseList),
erlang:display(NotFalse),
erlang:display(Number),
erlang:display(Last),
if
Last == false -> enumarate(Limit, lists:append(List, [NotFalse+2]));
Last =< Limit -> enumarate(Limit, lists:append(List, [list_to_integer(Number)+1]));
Last > Limit -> List
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment