icyrock.com

Home

PureScript solution to Project Euler problem 16

2019-Jan-01 02:59
purescriptproject-euler

Problem details at Project Euler problem 16 page.

Test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module Euler016Test (euler16suite) where
 
import Prelude
 
import Data.BigInt (fromString)
import Euler016 (euler16)
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Assert as Assert
 
euler16suite :: forall e. TestSuite e
euler16suite =
  suite "Euler 16" do
    test "Warmup" do
      Assert.equal 26 (euler16 15)
    test "Real" do
      Assert.equal 1366 (euler16 1000)

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
module Euler016 (euler16) where
 
import Prelude
 
import Data.Array ((:))
import Data.BigInt (BigInt, fromInt, pow, toNumber)
import Data.Foldable (sum)
import Data.Int (floor)
 
digits :: BigInt -> Array Int
digits n
  | n == fromInt 0 = []
  | otherwise      = xi : digits (n / fromInt 10)
    where x = n `mod` (fromInt 10)
          xi = (floor <<< toNumber) x
 
euler16 :: Int -> Int
euler16 n = sum $ digits $ pow (fromInt 2) (fromInt n)