Skip to content

Instantly share code, notes, and snippets.

@farhaven
Created August 7, 2012 21:58
Show Gist options
  • Save farhaven/3289739 to your computer and use it in GitHub Desktop.
Save farhaven/3289739 to your computer and use it in GitHub Desktop.
-module(p23).
-export([solution/0, solution/1]).
-define(LIMIT, 28123).
divisors(N) ->
Limit = round(math:sqrt(N)),
if
Limit < 2 -> [];
true ->
L1 = [ X || X <- lists:seq(2, Limit), N rem X =:= 0 ],
lists:usort(lists:append([[ 1 ], L1, lists:map(fun (X) -> N div X end, L1)]))
end.
property(N) ->
X = lists:sum(divisors(N)),
if
X < N -> deficient;
X > N -> abundant;
true -> perfect
end.
abundantNumbers(N) ->
lists:filter(fun(X) -> property(X) =:= abundant end, lists:seq(12, N)).
is_abundant_sum(N, Abundant) ->
L = lists:takewhile(fun(X) -> X < N end, Abundant),
lists:any(fun(X) -> X end,
lists:map(fun (X) -> lists:member(N - X, L) end, L)).
solution(N, _, N, A) ->
S = is_abundant_sum(N, A),
case S of
false -> N;
true -> 0
end;
solution(X, P, N, A) ->
S = is_abundant_sum(X, A),
if
P > N / 100 -> P2 = 0, io:format("\r~p% ~p/~p ", [ round(X / N * 100), N - X, N ]);
true -> P2 = P + 1
end,
case S of
false ->
X + solution(X + 1, P2, N, A);
true ->
solution(X + 1, P2, N, A)
end.
solution(N) ->
Abundant = abundantNumbers(N),
X = solution(0, 0, N, Abundant),
io:format("~n~p~n", [ X ]).
solution() -> solution(?LIMIT).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment