euler/Problem044.hs

20 lines
725 B
Haskell
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{-# LANGUAGE ScopedTypeVariables #-}
import Euler
-- Pentagonal numbers are generated by the formula, P[n]=n(3n1)/2.
--
-- Find the pair of pentagonal numbers, P[j] and P[k], for which their sum and
-- difference are pentagonal and D = |P[k] P[j]| is minimised; what is the value
-- of D?
pentagonals = map (\n -> n * (3*n - 1) `div` 2) [1..]
isPentagonal x = let n = (sqrt (24 * fromIntegral x + 1) + 1) / 6 in n == fromIntegral (floor n) && n > 0
main = print $ minimum $ do
-- Assumption: The solution will not require considering pentagonals over 10^7.
b <- takeWhile (< 10000000) pentagonals
a <- takeWhile (< b) pentagonals
guard $ isPentagonal (a + b)
guard $ isPentagonal (b - a)
return $ b - a