/extra/project-euler/055/055.factor

http://github.com/abeaumont/factor · Factor · 69 lines · 18 code · 20 blank · 31 comment · 4 complexity · e7f2bf38942ca987fcace45ecac28517 MD5 · raw file

  1. ! Copyright (c) 2008 Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: kernel math math.parser math.ranges project-euler.common sequences ;
  4. IN: project-euler.055
  5. ! http://projecteuler.net/index.php?section=problems&id=55
  6. ! DESCRIPTION
  7. ! -----------
  8. ! If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
  9. ! Not all numbers produce palindromes so quickly. For example,
  10. ! 349 + 943 = 1292,
  11. ! 1292 + 2921 = 4213
  12. ! 4213 + 3124 = 7337
  13. ! That is, 349 took three iterations to arrive at a palindrome.
  14. ! Although no one has proved it yet, it is thought that some numbers, like 196,
  15. ! never produce a palindrome. A number that never forms a palindrome through
  16. ! the reverse and add process is called a Lychrel number. Due to the
  17. ! theoretical nature of these numbers, and for the purpose of this problem, we
  18. ! shall assume that a number is Lychrel until proven otherwise. In addition you
  19. ! are given that for every number below ten-thousand, it will either (i) become a
  20. ! palindrome in less than fifty iterations, or, (ii) no one, with all the
  21. ! computing power that exists, has managed so far to map it to a palindrome. In
  22. ! fact, 10677 is the first number to be shown to require over fifty iterations
  23. ! before producing a palindrome: 4668731596684224866951378664 (53 iterations,
  24. ! 28-digits).
  25. ! Surprisingly, there are palindromic numbers that are themselves Lychrel
  26. ! numbers; the first example is 4994.
  27. ! How many Lychrel numbers are there below ten-thousand?
  28. ! NOTE: Wording was modified slightly on 24 April 2007 to emphasise the
  29. ! theoretical nature of Lychrel numbers.
  30. ! SOLUTION
  31. ! --------
  32. <PRIVATE
  33. : add-reverse ( n -- m )
  34. dup number>digits reverse 10 digits>integer + ;
  35. : (lychrel?) ( n iteration -- ? )
  36. dup 50 < [
  37. [ add-reverse ] dip over palindrome?
  38. [ 2drop f ] [ 1 + (lychrel?) ] if
  39. ] [
  40. 2drop t
  41. ] if ;
  42. : lychrel? ( n -- ? )
  43. 1 (lychrel?) ;
  44. PRIVATE>
  45. : euler055 ( -- answer )
  46. 10000 iota [ lychrel? ] count ;
  47. ! [ euler055 ] 100 ave-time
  48. ! 478 ms ave run time - 30.63 SD (100 trials)
  49. SOLUTION: euler055