icyrock.com

Home

PureScript solution to Project Euler problem 30

2020-Mar-08 09:17
purescriptproject-euler

Problem details at Project Euler problem 30 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module Euler030Test (euler30suite) where
 
import Prelude
 
import Euler030 (euler30)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler30suite :: TestSuite
euler30suite =
  suite "Euler 30" do
    test "Warmup" do
      Assert.equal 19316 (euler30 4 9474)
    test "Real" do
      Assert.equal 443839 (euler30 5 194979)

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
module Euler030 where
 
import Prelude
 
import Data.Array (cons, filter, range)
import Data.Foldable (sum)
import Data.Int (pow)
 
digits :: Int -> Array Int
digits n
  | n < 10    = [n]
  | otherwise = cons (n `mod` 10) (digits $ n / 10)
 
pdsum :: Int -> Int -> Int
pdsum m n = sum $ map (\j -> pow j m) $ digits n
 
wanted :: Int -> Int -> Boolean
wanted m n = pdsum m n == n
 
euler30 :: Int -> Int -> Int
euler30 m n = sum $ filter (wanted m) (range 2 n)