Skip to content

Instantly share code, notes, and snippets.

@farhaven
Created June 18, 2012 19:11
Show Gist options
  • Save farhaven/2950137 to your computer and use it in GitHub Desktop.
Save farhaven/2950137 to your computer and use it in GitHub Desktop.
-module(p3).
-export([prime_sieve/1, solution/0, solution/1]).
% generate a list of all primes smaller than N
prime_sieve(N) when is_integer(N) ->
prime_sieve([ 2 ] ++ [ X || X <- lists:seq(3, N) ]);
prime_sieve([]) -> [];
prime_sieve([H|C]) ->
[ H ] ++ prime_sieve(lists:filter(fun(X)-> (X rem H) /= 0 end, C)).
solution(_, [], F) -> F;
solution(N, [H|P], F) ->
case N rem H of
0 ->
io:format("prime factor ~p found~n", [ H ]),
solution(N div H, P, [ H ] ++ F);
_ -> solution(N, P, F)
end.
solution(N) ->
io:format("Generating primes... "),
P = prime_sieve(round(math:sqrt(N))),
io:format("done, testing~n"),
solution(N, P, []).
% what is the largest prime factor of 600851475143?
solution() ->
lists:max(solution(600851475143)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment