Skip to content

Commit

Permalink
Improve Project Euler problem 092 solution 1 (TheAlgorithms#5703)
Browse files Browse the repository at this point in the history
* Fix typos

* Improve solution
  • Loading branch information
MaximSmolskiy authored Oct 31, 2021
1 parent 568425d commit f92eac9
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions project_euler/problem_092/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@
"""


DIGITS_SQUARED = [digit ** 2 for digit in range(10)]


def next_number(number: int) -> int:
"""
Returns the next number of the chain by adding the square of each digit
to form a neww number.
For example if number = 12, next_number() will return 1^2 + 2^2 = 5.
to form a new number.
For example, if number = 12, next_number() will return 1^2 + 2^2 = 5.
Therefore, 5 is the next number of the chain.
>>> next_number(44)
32
Expand All @@ -27,31 +30,37 @@ def next_number(number: int) -> int:
"""
sum_of_digits_squared = 0
while number:
sum_of_digits_squared += (number % 10) ** 2
sum_of_digits_squared += DIGITS_SQUARED[number % 10]
number //= 10

return sum_of_digits_squared


CHAINS = {1: True, 58: False}


def chain(number: int) -> bool:
"""
The function generates the chain of numbers until the next number is 1 or 89.
For example, if starting number is 44, then the function generates the
following chain of numbers:
44 → 32 → 13 → 10 → 1 → 1.
Once the next number generated is 1 or 89, the function returns whether
or not the the next number generated by next_number() is 1.
or not the next number generated by next_number() is 1.
>>> chain(10)
True
>>> chain(58)
False
>>> chain(1)
True
"""
while number != 1 and number != 89:
number = next_number(number)
if number in CHAINS:
return CHAINS[number]

number_chain = chain(next_number(number))
CHAINS[number] = number_chain

return number == 1
return number_chain


def solution(number: int = 10000000) -> int:
Expand Down

0 comments on commit f92eac9

Please sign in to comment.