icyrock.com

Home

PureScript solution to Project Euler problem 21

2019-Jun-01 07:36
purescriptproject-euler

Problem details at Project Euler problem 21 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module Euler021Test (euler21suite) where
 
import Prelude
 
import Euler021 (euler21)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler21suite :: TestSuite
euler21suite =
  suite "Euler 21" do
    test "Warmup" do
      Assert.equal 504 (euler21 285)
    test "Real" do
      Assert.equal 31626 (euler21 10000)

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
module Euler021 where
 
import Prelude
 
import Control.MonadZero (guard)
import Data.Array (filter, range, (!!))
import Data.Foldable (sum)
import Data.Maybe (fromMaybe)
 
divSum :: Int -> Int
divSum n =
  let f m = n `mod` m == 0
  in sum $ filter f (range 1 (n - 1))
 
ami :: Array Int -> Int -> Boolean
ami ds n = fromMaybe false do
  vn <- ds !! n
  guard $ vn /= n
  vm <- ds !! vn
  pure $ vm == n
 
euler21 :: Int -> Int
euler21 n =
  let ds = divSum <$> (range 0 (n - 1))
      as = filter (ami ds) (range 1 (n - 1))
  in sum as