This is the naive doubly recursive solution. Speed would be greatly improved by use of [[memoization]], dynamic programming, or the closed form.

This is the naive doubly recursive solution. Speed would be greatly improved by use of [[memoization]], dynamic programming, or the closed form.

<haskell>

<haskell>

−

problem_31 =

+

problem_31 = ways [1,2,5,10,20,50,100,200] !!200

−

ways [1,2,5,10,20,50,100,200] !!200

+

where ways [] = 1 : repeat 0

−

where

+

ways (coin:coins) =n

−

ways [] = 1 : repeat 0

+

where n = zipWith (+) (ways coins) (replicate coin 0 ++ n)

−

ways (coin:coins) =n

+

−

where

+

−

n = zipWith (+) (ways coins) (take coin (repeat 0) ++ n)

+

</haskell>

</haskell>

Line 21:

Line 18:

combinations = foldl (\without p ->

combinations = foldl (\without p ->

let (poor,rich) = splitAt p without

let (poor,rich) = splitAt p without

−

with = poor ++

+

with = poor ++ zipWith (++) (map (map (p:)) with)

−

zipWith (++) (map (map (p:)) with)

+

rich

−

rich

+

in with

in with

) ([[]] : repeat [])

) ([[]] : repeat [])

−

problem_31 =

+

problem_31 = length $ combinations coins !! 200

−

length $ combinations coins !! 200

+

</haskell>

+

+

The above may be ''a beautiful solution'', but I couldn't understand it without major mental gymnastics. I would like to offer the following, which I hope will be easier to follow for ordinary ''mentats'' -- HenryLaxen 2008-02-22

+

<haskell>

+

coins = [1,2,5,10,20,50,100,200]

+

+

withcoins 1 x = [[x]]

+

withcoins n x = concatMap addCoin [0 .. x `div` coins!!(n-1)]

+

where addCoin k = map (++[k]) (withcoins (n-1) (x - k*coins!!(n-1)) )

+

+

problem_31 = length $ withcoins (length coins) 200

+

</haskell>

+

+

The program above can be slightly modified as shown below so it just counts the combinations without generating them.

Using isPrime from above, and observing that one that can greatly reduce the search space because no circular prime can contain an even number, nor a 5, since eventually such a digit will be at the end of the number, and

The above may be a beautiful solution, but I couldn't understand it without major mental gymnastics. I would like to offer the following, which I hope will be easier to follow for ordinary mentats -- HenryLaxen 2008-02-22

Using isPrime from above, and observing that one that can greatly reduce the search space because no circular prime can contain an even number, nor a 5, since eventually such a digit will be at the end of the number, and
hence composite, we get: (HenryLaxen 2008-02-27)