Skip to content

Instantly share code, notes, and snippets.

@Wollw
Last active December 12, 2015 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wollw/4748143 to your computer and use it in GitHub Desktop.
Save Wollw/4748143 to your computer and use it in GitHub Desktop.
Project Euler Problem 45 This is mostly unoptimized and terribly slow. Takes about 40 seconds on my i5-3320M.
-- Project Euler Problem 45
--
-- Triangle, pentagonal, hexagonal
--
-- Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
-- Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
-- Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
-- Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
--
-- It can be verified that T285 = P165 = H143 = 40755.
--
-- Find the next triangle number that is also pentagonal and hexagonal.
main = print . head $ triPentHex
triPentHex :: [Integer]
triPentHex = filter isPentHex triangles
where
triangles = dropWhile (<=40755) $ scanl1 (+) [1..]
pentagonals = dropWhile (<=40755) $ scanl1 (+) [1,4..]
hexagonals = dropWhile (<=40755) $ scanl1 (+) [1,5..]
elemOrdered ys x = elem x $ takeWhile (<=x) ys
isPentHex x = (elemOrdered hexagonals x) && (elemOrdered pentagonals x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment