Skip to content

Improve Project Euler problem 092 solution 1 #5703

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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