|
| 1 | +""" |
| 2 | +If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. |
| 3 | +Not all numbers produce palindromes so quickly. For example, |
| 4 | +349 + 943 = 1292, |
| 5 | +1292 + 2921 = 4213 |
| 6 | +4213 + 3124 = 7337 |
| 7 | +That is, 349 took three iterations to arrive at a palindrome. |
| 8 | +Although no one has proved it yet, it is thought that some numbers, like 196, |
| 9 | +never produce a palindrome. A number that never forms a palindrome through the |
| 10 | +reverse and add process is called a Lychrel number. Due to the theoretical nature |
| 11 | +of these numbers, and for the purpose of this problem, we shall assume that a number |
| 12 | +is Lychrel until proven otherwise. In addition you are given that for every number |
| 13 | +below ten-thousand, it will either (i) become a palindrome in less than fifty |
| 14 | +iterations, or, (ii) no one, with all the computing power that exists, has managed |
| 15 | +so far to map it to a palindrome. In fact, 10677 is the first number to be shown |
| 16 | +to require over fifty iterations before producing a palindrome: |
| 17 | +4668731596684224866951378664 (53 iterations, 28-digits). |
| 18 | +
|
| 19 | +Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; |
| 20 | +the first example is 4994. |
| 21 | +How many Lychrel numbers are there below ten-thousand? |
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +def is_palindrome(n: int) -> bool: |
| 26 | + """ |
| 27 | + Returns True if a number is palindrome. |
| 28 | + >>> is_palindrome(12567321) |
| 29 | + False |
| 30 | + >>> is_palindrome(1221) |
| 31 | + True |
| 32 | + >>> is_palindrome(9876789) |
| 33 | + True |
| 34 | + """ |
| 35 | + return str(n) == str(n)[::-1] |
| 36 | + |
| 37 | + |
| 38 | +def sum_reverse(n: int) -> int: |
| 39 | + """ |
| 40 | + Returns the sum of n and reverse of n. |
| 41 | + >>> sum_reverse(123) |
| 42 | + 444 |
| 43 | + >>> sum_reverse(3478) |
| 44 | + 12221 |
| 45 | + >>> sum_reverse(12) |
| 46 | + 33 |
| 47 | + """ |
| 48 | + return int(n) + int(str(n)[::-1]) |
| 49 | + |
| 50 | + |
| 51 | +def compute_lychrel_nums(limit: int) -> int: |
| 52 | + """ |
| 53 | + Returns the count of all lychrel numbers below limit. |
| 54 | + >>> compute_lychrel_nums(10000) |
| 55 | + 249 |
| 56 | + >>> compute_lychrel_nums(5000) |
| 57 | + 76 |
| 58 | + >>> compute_lychrel_nums(1000) |
| 59 | + 13 |
| 60 | + """ |
| 61 | + lychrel_nums = [] |
| 62 | + for num in range(1, limit): |
| 63 | + iterations = 0 |
| 64 | + a = num |
| 65 | + while iterations < 50: |
| 66 | + num = sum_reverse(num) |
| 67 | + iterations += 1 |
| 68 | + if is_palindrome(num): |
| 69 | + break |
| 70 | + else: |
| 71 | + lychrel_nums.append(a) |
| 72 | + return len(lychrel_nums) |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + print(f"{compute_lychrel_nums(10000) = }") |
0 commit comments