Skip to content

Commit f92eac9

Browse files
Improve Project Euler problem 092 solution 1 (TheAlgorithms#5703)
* Fix typos * Improve solution
1 parent 568425d commit f92eac9

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

project_euler/problem_092/sol1.py

+16-7
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@
1212
"""
1313

1414

15+
DIGITS_SQUARED = [digit ** 2 for digit in range(10)]
16+
17+
1518
def next_number(number: int) -> int:
1619
"""
1720
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.
2023
Therefore, 5 is the next number of the chain.
2124
>>> next_number(44)
2225
32
@@ -27,31 +30,37 @@ def next_number(number: int) -> int:
2730
"""
2831
sum_of_digits_squared = 0
2932
while number:
30-
sum_of_digits_squared += (number % 10) ** 2
33+
sum_of_digits_squared += DIGITS_SQUARED[number % 10]
3134
number //= 10
3235

3336
return sum_of_digits_squared
3437

3538

39+
CHAINS = {1: True, 58: False}
40+
41+
3642
def chain(number: int) -> bool:
3743
"""
3844
The function generates the chain of numbers until the next number is 1 or 89.
3945
For example, if starting number is 44, then the function generates the
4046
following chain of numbers:
4147
44 → 32 → 13 → 10 → 1 → 1.
4248
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.
4450
>>> chain(10)
4551
True
4652
>>> chain(58)
4753
False
4854
>>> chain(1)
4955
True
5056
"""
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
5362

54-
return number == 1
63+
return number_chain
5564

5665

5766
def solution(number: int = 10000000) -> int:

0 commit comments

Comments
 (0)