I'm quite new to Haskell, and to learn it better I started solving problems here and there and I ended up with this (project Euler 34).
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial >of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
I wrote a C and an Haskell brute force solution.
Could someone explain me the Haskell version is ~15x (~0.450 s vs ~6.5s )slower than the C implementation and how to possibly tune and speedup the Haskell solution?
unsigned int solve(){ unsigned int result = 0; unsigned int i=10; while(i<2540161){ unsigned int sumOfFacts = 0; unsigned int number = i; while (number > 0) { unsigned int d = number % 10; number /= 10; sumOfFacts += factorial(d); } if (sumOfFacts == i) result += i; i++; } return result; } here the haskell solution
--BRUTE FORCE SOLUTION solve:: Int solve = sum (filter (\x-> sfc x 0 == x) [10..2540160]) --sum factorial of digits sfc :: Int -> Int -> Int sfc 0 acc = acc sfc n acc = sfc n' (acc+fc r) where n' = div n 10 r = mod n 10 --n-(10*n') fc 0 =1 fc 1 =1 fc 2 =2 fc 3 =6 fc 4 =24 fc 5 =120 fc 6 =720 fc 7 =5040 fc 8 =40320 fc 9 =362880
-O?-O2runs in 0.55s on my computer