Skip to content

Instantly share code, notes, and snippets.

@aleqsio
Created April 19, 2018 21:37
Show Gist options
  • Save aleqsio/38120cf6b83a2ae9b6c03ccf5711ad9a to your computer and use it in GitHub Desktop.
Save aleqsio/38120cf6b83a2ae9b6c03ccf5711ad9a to your computer and use it in GitHub Desktop.
Task nr. 1 for SW recuruitment
%%%-------------------------------------------------------------------
%%% @author Aleksander Mikucki
%%% Created : 19. kwi 2018 17:02
%%%-------------------------------------------------------------------
-module(task1).
-author("Aleksander Mikucki").
-export([get_special_difference/2]).
get_special_difference(A, B) -> PrimeMap = filter_occurring_prime_times(list_to_occurrence_count(B)),
lists:filter(fun(X) -> not maps:is_key(X, PrimeMap) end, A).
filter_occurring_prime_times(Occurrences) -> maps:filter(fun(_, V) -> is_prime(V) end, Occurrences).
list_to_occurrence_count(List) -> count_occurrence(List, maps:new()).
count_occurrence([], Occurrences) -> Occurrences;
count_occurrence([H | T], Occurrences) -> count_occurrence(T, maps:update_with(H, fun(X) -> X + 1 end, 1, Occurrences)).
is_prime(0) -> false;
is_prime(1) -> false;
is_prime(2) -> true;
is_prime(V) when V < 2047 -> miller_rabin(factorise_mr(V), V, [2]);
is_prime(V) when V < 25326001 -> miller_rabin(factorise_mr(V), V, [2, 3, 5]);
is_prime(V) when V < 2152302898747 -> miller_rabin(factorise_mr(V), V, [2, 3, 5, 7, 11]).
miller_rabin(_, _, []) -> true;
miller_rabin({D, S}, N, [Check | Remaining]) ->
not ((power(Check, D) rem N /= 1) and lists:foldl(fun(R, Acc) ->
(Acc and (power(Check, power(2, R) * D) rem N /= N - 1)) end, true, lists:seq(0, max_of(0, S - 1))))
and miller_rabin({D, S}, N, Remaining).
factorise_mr(N) -> factorise_mr(N - 1, 0).
factorise_mr(D, S) when D rem 2 == 0 -> factorise_mr(D div 2, S + 1);
factorise_mr(D, S) -> {D, S}.
max_of(X, Y) when X > Y -> X; max_of(_, Y) -> Y.
power(X, Y) -> power(X, Y, 1).
power(_, 0, Acc) -> Acc;
power(X, Y, Acc) when Y rem 2 == 1 -> power(X, Y - 1, Acc * X);
power(X, Y, Acc) -> power(X * X, Y div 2, Acc).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment