Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

44 lines (35 sloc) 1.091 kB
%% Problem
%% ---------------------
%% Pentagonal numbers are generated by the formula, Pn=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 P4 + P7 = 22 + 70 = 92 = P8. However, their
%% difference, 70 - 22 = 48, is not pentagonal.
%%
%% Find the pair of pentagonal numbers, Pj and Pk, for which their
%% sum and difference is pentagonal and D = |Pk - Pj| is minimised;
%% what is the value of D?
%% ---------------------
-module(p044).
-export([solve/0]).
-include_lib("eunit/include/eunit.hrl").
solve() -> pent(1, 1, []).
%% P(n+1) = P(n) + 3n + 1
%%
pent(N, P, Ps) ->
List = [ P-X || X <- Ps, is_pentagonal(P-X), is_pentagonal(P+X) ],
case List of
[] -> pent(N+1, P+3*N+1, [P|Ps]);
_ -> List
end.
%% http://en.wikipedia.org/wiki/Pentagonal_number
%%
is_pentagonal(X) ->
N = (math:sqrt(24*X+1) + 1) / 6,
N == trunc(N).
is_pentagonal_true_test() ->
?assertEqual(true, is_pentagonal(92)).
is_pentagonal_false_test() ->
?assertEqual(false, is_pentagonal(91)).
Jump to Line
Something went wrong with that request. Please try again.