Question
Pentagonal numbers are generated by the formula, . The first ten pentagonal numbers are:
It can be seen that . However, their difference, , is not pentagonal.
Find the pair of pentagonal numbers, and , for which their sum and difference is pentagonal and is minimised; what is the value of ?
Haskell
import qualified Data.Set as Set
pentagonals :: [Int]
pentagonals = [(n*(3*n - 1)) `quot` 2 | n <- [1..3000]]
isPentagonal :: Int -> Bool
isPentagonal n = Set.member n (Set.fromList pentagonals)
candidates :: [Int]
candidates = [j - k | j <- pentagonals, k <- takeWhile (< j) pentagonals,
isPentagonal (j - k), isPentagonal (j + k)]
main :: IO ()
main = print $ head candidates
$ ghc -O2 -o pentagonal-nums pentagonal-nums.hs
$ time ./pentagonal-nums
real 0m0.164s
user 0m0.156s
sys 0m0.008s
Python
#!/usr/bin/env python
from itertools import *
from math import *
from operator import *
def pentagonal(n):
return n*(3*n-1)//2
def main():
pentagonals = set(pentagonal(n) for n in range(1, 3000))
c = combinations(pentagonals, 2)
for p in c:
if add(*p) in pentagonals and abs(sub(*p)) in pentagonals:
print(abs(sub(*p)))
if __name__ == "__main__":
main()