Home

PureScript solution to Project Euler problem 44

2021-May-29 09:40
purescriptproject-euler

Problem details at Project Euler problem 44 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module Euler044Test (euler44suite) where
 
import Prelude
 
import Data.Maybe (Maybe(..))
import Euler044 (euler44, pentagonals)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler44suite :: TestSuite
euler44suite =
  suite "Euler 44" do
    test "Warmup" do
      Assert.equal [1, 5, 12, 22, 35, 51, 70, 92, 117, 145] (pentagonals 10)
 
    test "Real" do
      Assert.equal (Just 5482660) (euler44 2500)

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module Euler044 where
 
import Prelude
 
import Control.MonadZero (guard)
import Data.Array (range)
import Data.Foldable (minimum)
import Data.Maybe (Maybe)
import Data.Set as S
 
pentagonals :: Int -> Array Int
pentagonals n =
  let f j = j * (3 * j - 1) / 2
  in map f (range 1 n)
 
euler44 :: Int -> Maybe Int
euler44 n = minimum do
  let ps = pentagonals n
      sps = S.fromFoldable ps
  j <- ps
  k <- ps
  guard $ S.member (k + j) sps && S.member (k - j) sps
  pure $ k - j