I've "solved" Project Euler Question 4 and I was wondering if I could make my answer more efficient (I'm using Project Euler to help me learn Haskell).
The problem reads:
Find the largest palindrome made from the product of two 3-digit numbers
Here is my solution
getMaxPalindrome = maximum[x*y | x<-[100..999], y<-[100..999], reverse(show(x*y)) ==show(x*y)]
All suggestions for improvement are appreciated!
1 Answer 1
First, since *
is commutative, you can save 1/2 of your computation if you restrict yourself to cases where x >= y
:
[ x*y | x<-[100..999], y<-[100..x], ... ]
Second, if you could generate all the products in a non-increasing list, you'd just be searching for the first element of such a list satisfying the predicate, which would also speed the search very much. See data-ordlist package, which implements many useful functions on sorted lists, in particular in your case you'll probably need unionBy
or unionAllBy
Explore related questions
See similar questions with these tags.