Contents

The most straightforward solution, following the logical structure closely, actually generating the solutions (won't be the optimal one obviously by a long shot, but serves as an illustration, a development aid... runs in under 0.5 second on Ideone). We can make up the sum either with or without the most valuable coin:

p31=length$g200[200,100,50,20,10,5,2,1]whereg0_=[[]]-- exactly one way to get 0 sum, with no coins at allgn[]=[]-- no way to sum up no coins to a non-zero sumgncoins@(c:rest)|c<=n=map(c:)(g(n-c)coins)-- with the top coin++gnrest|otherwise=gnrest-- without it

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

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

importData.ArrayimportData.List{-The key comes in realizing that N*9! < 10^N when N >= 9, so weonly have to check up to 9 digit integers. The other key isthat addition is commutative, so we only need to generatecombinations (with duplicates) of the sums of the variousfactorials. These sums are the only potential "curious" sums.-}facn=a!nwherea=listArray(0,9)(1:(scanl1(*)[1..9]))-- subsets of size k, including duplicatescombinationsOf0_=[[]]combinationsOf_[]=[]combinationsOfk(x:xs)=map(x:)(combinationsOf(k-1)(x:xs))++combinationsOfkxsintToListn=reverse$unfoldr(\x->ifx==0thenNothingelseJust(x`mod`10,x`div`10))nisCurious(n,l)=sort(intToListn)==l-- Turn a list into the sum of the factorials of the digitsfactorialSuml=sum$mapfaclpossiblyCurious=map(\z->(factorialSumz,z))curiousn=filterisCurious$possiblyCurious$combinationsOfn[0..9]problem_34=sum$(fst.unzip)$concatMapcurious[2..9]

(The wiki formatting is messing up the unzip">unzip line above, it is correct in the version I typed in. It should of course just be fst . unzip)

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)

importControl.Monad(replicateM)canBeCircularPrimeList=[1,3,7,9]listToIntn=foldl(\xy->10*x+y)0nrotnl=y++xwhere(x,y)=splitAtnlallrotsl=map(\x->rotxl)[0..(lengthl)-1]isCircularl=all(isPrime.listToInt)$allrotslcircular1=[[2],[3],[5],[7]]-- a slightly special casecircularn=filterisCircular$replicateMncanBeCircularPrimeListproblem_35=length$concatMapcircular[1..6]