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 are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
In [21]:
// yet another inefficient one based on guesswork
let max = 10000L
let pentagonal n = (n * ((3L*n)-1L)) / 2L
let pentagonLookup = [ 1L..max ] |> List.map pentagonal |> Set.ofList
let pentagons = seq { 1L..max } |> Seq.map pentagonal
let pentagons2 = seq { 1L..max } |> Seq.map pentagonal // needed?
let pairWith seq x =
seq |> Seq.map (fun y -> (x,y))
pentagons
|> Seq.map (pairWith pentagons2)
|> Seq.concat
|> Seq.filter (fun (x,y) -> x <> y)
|> Seq.filter (fun (x,y) -> pentagonLookup.Contains(abs(x-y)))
|> Seq.filter (fun (x,y) -> pentagonLookup.Contains(abs(x+y)))
|> Seq.map (fun (x,y) -> ((x,y), (x-y)))
|> Seq.sortBy (fun (x,y) -> x)
Out[21]: