1

I am doing Project Euler question 55 on Lychrel numbers where the aim is to find the number of Lychrel numbers below 10,000 within 50 iterations. I came up with this:

revAdd n = (read $ reverse $ show n) + n

lychrel n | length xs == 50 = error "False"
          | ((reverse $ show (revAdd n)) == (show (revAdd n)))  = True
          | otherwise  = (lychrel (revadd n) ) : xs

answer = length [ x | x <- [1..10000] , lychrel x == True]

But I don't know how to define xs as the list of previous iterations upon n, which are when n is not a palindrome. How would I do this, and secondly would this work?

1
  • 2
    Useless boolean comparison to True. Remember, something == True = something; something == False == not something. I hate it when people do this in any language. Commented Oct 23, 2009 at 16:12

2 Answers 2

3

It becomes much easier if you separate your concerns into distinct steps.

  1. Define a function that sums a number and its reverse.
  2. Use iterate to repeat your number, starting from x.
  3. Use take to limit your iteration to 50 steps.
  4. Use all with a predicate to determine if any of these steps results in a palindrome.
Sign up to request clarification or add additional context in comments.

1 Comment

Duh, of course I meant any not all. Basically the same thing, though; De Morgan's Law any p = or . map p = not . and . map (not . p) = not . all (not . p)
2

You need to pass the list of iterations (or just the number of iterations) in as a parameter to lychrel, starting with [] in the call from answer and adding to it in the recursive call in the otherwise case. Look up "accumulating parameters" for more general background on this technique.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.