module Problem138 where

main :: IO ()
-- h-b=+-1 => (h-b)^2=1
-- h^2+b^2/4=L^2
--   h   b b/2
-- 273 272 136
--  15  16   8
-- h, b/2 form a pythagorean triple
-- h, b/2 = k(m^2-n^2), 2kmn or 2kmn, k(m^2-n^2)
-- (k(m^2-n^2)-4kmn)^2=1 or (2kmn-2k(m^2-n^2))^2=1
-- k^2(m^2-n^2-4mn)^2=1 or 4k^2(mn-m^2-n^2)^2=1
-- k must be 1 & second equation is not valid
-- m^2-n^2-4mn = +-1
-- e.g. 15,8,17 → m=4,n=1,k=1,m^2-n^2-4mn=-1
-- e.g. 273,136,305 → m=17,n=4,k=1,m^2-n^2-4mn=1
-- Solving diophantine: x^2-y^2-4xy = +-1
-- (x-2y)^2 - 5y^2 = +-1
-- let X = x-2y, Y = y
-- X^2-5Y^2 = +-1
-- (+1) → one solution is (9,4) other solutions
-- → (x',y')=(9x+20y,4x+9y)
-- (-1) → one solution is (2,1) other solutions →
-- → (X',Y')=(2x'+5y',y'+2x')
main = print . sum . take 12 . getSolutions $ merge seriesPositive seriesNegative
  where
    seriesPositive = iterate (\(x, y) -> (9 * x + 20 * y, 4 * x + 9 * y)) (1, 0)
    seriesNegative = map (\(x, y) -> (2 * x + 5 * y, x + 2 * y)) seriesPositive
    getSolutions =
        map (\(h, b2) -> floor . sqrt $ h * h + b2 * b2)
            . filter (\(h, b2) -> h > 0 && b2 > 0)
            . map
                ( (\(m, n) -> (m * m - n * n, 2 * m * n))
                . (\(x, y) -> (x + 2 * y, y))
                )
    merge l1@(x : xs) l2@(y : ys)
        | x < y     = x : merge xs l2
        | otherwise = y : merge l1 ys
