--------------------------------------------------------------------------------
-- Triangular, pentagonal, and hexagonal
-- Problem 45
-- 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.
--------------------------------------------------------------------------------

import Math.NumberTheory.Powers.Squares

hex :: Integer -> Integer
hex n = n * (2*n -1)

tri :: Integer -> Integer
tri n = n * (n+1) `div` 2

is_pent :: Integer -> Bool
is_pent x = (isSquare p) && ((mod q 6) == 5)
  where
    p = (24*x) + 1
    q = integerSquareRoot p

solve n
  | is_pent $ hex n = (n,hex n,m,tri m)
  | True = solve (n+1)
  where
    m = 2*n -1
    
main = do
  print $ map hex [1..5]
  print $ map tri [1..5]
  print $ map is_pent [1,5,12,22,35,40755]
  print $ solve 2
  print $ solve 144

{-
Every hexagonal number is also a triangular number, and of the three
hexagonals increase the fastest.  So generate hexagonal number, test if it
is pentagonal, and adjust the subscript to get triangular number.
We will not know the subscript of the pentagonal number, but that is not 
required.
-}

