Project Euler 40,41

Problem 40

http://projecteuler.net/index.php?section=problems&id=40


こんないい加減な書き方でも意外と速い。実際にはリストを作っていないようだ。

s [] = ""
s (p:ps) = (show p) ++ (s ps)

mul :: [Char] -> [Int] -> Int -> Int
mul s [] k = 1
mul (c:cs) (p:ps) k | p == k = read([c]) * (mul (cs) ps (k + 1))
                    | otherwise = mul cs (p:ps) (k + 1)

n = 6
main = print(mul (s [1..]) (map (10^) [0..n]) 1)

Problem 41

http://projecteuler.net/index.php?section=problems&id=41


Data.ListにあるpermutationsはPythonと並びが逆なので注意が必要。例えば、

 *Main> take 4 (permutations [1..7])
[[1,2,3,4,5,6,7],[2,1,3,4,5,6,7],[3,2,1,4,5,6,7],[2,3,1,4,5,6,7]]

リストを逆にして順列を生成しないといけない。
順列を自作するとこんな感じ。

perm [] = [[]]
perm a = concat (map (\n -> map ([n]++) (perm (filter (/= n) a))) a)

これだとPythonと同じ並びになる。

import Data.List

is_prime n = all (\m -> mod n m /= 0)
            (takeWhile (\m -> m * m <= n) (2:[3,5..]))
numerize a = foldr (\x y -> x + y * 10) 0 a

p n = permutations [1,2..n]
a = foldr (\x y -> y ++ (p x)) [] [1..7]
main = print(head (filter is_prime (map numerize a)))