icyrock.com
HomePureScript solution to Project Euler problem 45
2021-Jun-15 18:06
Problem details at Project Euler problem 45 page.
Test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | module Euler045Test (euler45suite) where import Prelude import Data . BigInt as BI import Euler045 (euler45, hexagonals, pentagonals, triangles) import Test . Unit (TestSuite, suite, test) import Test . Unit . Assert as Assert euler45suite :: TestSuite euler45suite = suite "Euler 45" do test "Warmup" do Assert . equal (BI . fromInt < $ > [ 1 , 3 , 6 , 10 , 15 ]) (triangles 5 ) Assert . equal (BI . fromInt < $ > [ 1 , 5 , 12 , 22 , 35 ]) (pentagonals 5 ) Assert . equal (BI . fromInt < $ > [ 1 , 6 , 15 , 28 , 45 ]) (hexagonals 5 ) test "Real" do Assert . equal (BI . fromString "1533776805" ) (euler45 60000 ) |
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | module Euler045 where import Prelude import Control . MonadZero (guard) import Data . BigInt (BigInt) import Data . BigInt as BI import Data . Array ( drop , head , range) import Data . Maybe ( Maybe ) import Data . Set as S triangles :: Int - > Array BigInt triangles n = let f j = j * (j + BI . fromInt 1 ) / BI . fromInt 2 in map f (BI . fromInt < $ > range 1 n) pentagonals :: Int - > Array BigInt pentagonals n = let f j = j * (BI . fromInt 3 * j - BI . fromInt 1 ) / BI . fromInt 2 in map f (BI . fromInt < $ > range 1 n) hexagonals :: Int - > Array BigInt hexagonals n = let f j = j * (BI . fromInt 2 * j - BI . fromInt 1 ) in map f (BI . fromInt < $ > range 1 n) euler45 :: Int - > Maybe BigInt euler45 n = head do let ts = triangles n ps = pentagonals n sps = S . fromFoldable ps hs = hexagonals n shs = S . fromFoldable hs t < - drop 285 ts guard $ S . member t sps && S . member t shs pure $ t |