PageRenderTime 21ms CodeModel.GetById 12ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

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

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