icyrock.com

Home

PureScript solution to Project Euler problem 37

2020-Oct-05 13:36
purescriptproject-euler

Problem details at Project Euler problem 37 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
module Euler037Test (euler37suite) where
 
import Prelude
 
import Euler037 (euler37)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler37suite :: TestSuite
euler37suite =
  suite "Euler 37" do
    test "Real" do
      Assert.equal 748317 (euler37 unit)

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
37
38
39
40
41
module Euler037 where
 
import Prelude
 
import Data.Array (all, concat, concatMap, filter, (:))
import Data.Foldable (sum)
 
isPrime :: Int -> Boolean
isPrime n =
  let go j
        | j * j > n      = true
        | n `mod` j == 0 = false
        | otherwise      = go (j + 1)
  in n > 1 && go 2
 
rtruncs :: Unit -> Array Int
rtruncs _ =
  let radd l = (\j -> l * 10 + j) <$> [1, 3, 7, 9]
      rps ls = filter isPrime $ concatMap radd ls
      go acc ls =
        case rps ls of
          [] -> acc
          ps -> go (concat [acc, ps]) ps
  in go [] [2, 3, 5, 7]
 
ltruncs :: Int -> Array Int
ltruncs j =
  let go acc k m =
        case k `mod` m of
          0 -> acc
          l -> go (l : acc) k (m * 10)
  in go [] j 10
 
pltrunc :: Int -> Boolean
pltrunc = all isPrime <<< ltruncs
 
gen :: Unit -> Array Int
gen _ = (filter pltrunc <<< rtruncs) unit
 
euler37 :: Unit -> Int
euler37 = sum <<< gen