-
Notifications
You must be signed in to change notification settings - Fork 2
/
p44.erl
30 lines (24 loc) · 1.12 KB
/
p44.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
-module(p44).
-export([answer/0]).
%% Pentagonal numbers are generated by the formula, P(n)=n(3n−1)/2. The first ten pentagonal numbers are:
%% 1,5,12,22,35,51,70,92,117,145, ...
%% It can be seen that P(4) + P(7) = 22 + 70 = 92 = P(8). However, their difference, 70 − 22 = 48, is not pentagonal.
%% Find the pair of pentagonal numbers, P(j) and P(k), for which their sum and difference is pentagonal and D = |P(k) − P(j)| is minimised;
%% what is the value of D?
-compile(export_all).
answer() ->
[P | Ps] = [penta(N) || N <- lists:seq(2,2400)],
find_diff(P, Ps, 1000000000).
find_diff(_, [], Diff) -> Diff;
find_diff(J, Ps, Diff) ->
Ks = lists:filter(fun(K) ->
lists:member(J+K, Ps) andalso lists:member(K-J, Ps)
end, Ps),
Diff1 = lists:foldl(fun(K, D) ->
case abs(J-K) < D of
true -> abs(J-K);
false -> D
end
end, Diff, Ks),
find_diff(hd(Ps), tl(Ps), Diff1).
penta(N) -> N * ( 3 * N - 1 ) div 2.