/*
Euler #44 in Picat.
"""
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?
"""
This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com
See also my Picat page: http://www.hakank.org/picat/
*/
main => go.
go => time(euler44).
euler44 =>
garbage_collect(200_000_000),
% S = [pent(N) : N in 1..2500],
S = [N*(3*N-1) div 2 : N in 1..2500],
% T = new_map(2500,[V=1 : V in S]),
T = new_set(2500,S),
D = 10000000,
foreach(J in S.reverse(), K in S,
J < K,
A = J+K,
A < D,
T.has_key(A),
B = abs(J-K),
B < D,
T.has_key(B))
D := B
end,
println(D).
% slower
euler44b =>
garbage_collect(200_000_000),
% S = [pent(N) : N in 1..2500],
S = [N*(3*N-1) div 2 : N in 1..2500],
% T = new_map(2500,[V=1 : V in S]),
T = new_set(2500,S),
D = [B : J in S, K in S,
J < K,
A = J+K,
T.has_key(A),
B = abs(J-K),
T.has_key(B)],
println(D.first()).
pent(N) = N*(3*N-1) div 2.