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