12
12
"""
13
13
14
14
15
+ DIGITS_SQUARED = [digit ** 2 for digit in range (10 )]
16
+
17
+
15
18
def next_number (number : int ) -> int :
16
19
"""
17
20
Returns the next number of the chain by adding the square of each digit
18
- to form a neww number.
19
- For example if number = 12, next_number() will return 1^2 + 2^2 = 5.
21
+ to form a new number.
22
+ For example, if number = 12, next_number() will return 1^2 + 2^2 = 5.
20
23
Therefore, 5 is the next number of the chain.
21
24
>>> next_number(44)
22
25
32
@@ -27,31 +30,37 @@ def next_number(number: int) -> int:
27
30
"""
28
31
sum_of_digits_squared = 0
29
32
while number :
30
- sum_of_digits_squared += ( number % 10 ) ** 2
33
+ sum_of_digits_squared += DIGITS_SQUARED [ number % 10 ]
31
34
number //= 10
32
35
33
36
return sum_of_digits_squared
34
37
35
38
39
+ CHAINS = {1 : True , 58 : False }
40
+
41
+
36
42
def chain (number : int ) -> bool :
37
43
"""
38
44
The function generates the chain of numbers until the next number is 1 or 89.
39
45
For example, if starting number is 44, then the function generates the
40
46
following chain of numbers:
41
47
44 → 32 → 13 → 10 → 1 → 1.
42
48
Once the next number generated is 1 or 89, the function returns whether
43
- or not the the next number generated by next_number() is 1.
49
+ or not the next number generated by next_number() is 1.
44
50
>>> chain(10)
45
51
True
46
52
>>> chain(58)
47
53
False
48
54
>>> chain(1)
49
55
True
50
56
"""
51
- while number != 1 and number != 89 :
52
- number = next_number (number )
57
+ if number in CHAINS :
58
+ return CHAINS [number ]
59
+
60
+ number_chain = chain (next_number (number ))
61
+ CHAINS [number ] = number_chain
53
62
54
- return number == 1
63
+ return number_chain
55
64
56
65
57
66
def solution (number : int = 10000000 ) -> int :
0 commit comments